#!/bin/bash

# Lightning Auth Complete Example Setup Script
# This script helps you set up the example application

set -e

echo "⚡ Lightning Auth Complete Example Setup"
echo "========================================"

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo "❌ Node.js is not installed. Please install Node.js 18+ first."
    exit 1
fi

# Check Node.js version
NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
    echo "❌ Node.js version 18+ is required. Current version: $(node -v)"
    exit 1
fi

echo "✅ Node.js $(node -v) detected"

# Install dependencies
echo "📦 Installing dependencies..."
npm install

# Setup environment
echo "🔧 Setting up environment..."
if [ ! -f .env.local ]; then
    cp env.example .env.local
    echo "✅ Created .env.local from template"
    echo "⚠️  Please edit .env.local with your configuration"
else
    echo "✅ .env.local already exists"
fi

# Database setup
echo "🗄️ Setting up database..."

# Check if DATABASE_URL is set
if grep -q "DATABASE_URL" .env.local; then
    DATABASE_URL=$(grep "DATABASE_URL" .env.local | cut -d'=' -f2 | tr -d '"')
    
    if [[ "$DATABASE_URL" == *"postgresql"* ]]; then
        echo "🐘 PostgreSQL detected"
        echo "⚠️  Please ensure PostgreSQL is running and the database exists"
        echo "   You can create it with: createdb lightning_auth_example"
    elif [[ "$DATABASE_URL" == *"file:"* ]]; then
        echo "🗃️ SQLite detected"
    else
        echo "⚠️  Unknown database type in DATABASE_URL"
    fi
else
    echo "⚠️  DATABASE_URL not found in .env.local"
fi

# Generate Prisma client
echo "🔧 Generating Prisma client..."
npm run db:generate

# Run migrations
echo "🗄️ Running database migrations..."
npm run db:migrate

# Seed database
echo "🌱 Seeding database with sample data..."
npm run db:seed

echo ""
echo "🎉 Setup complete!"
echo ""
echo "Next steps:"
echo "1. Edit .env.local with your configuration"
echo "2. Run: npm run dev:lightning"
echo "3. Open: https://localhost:3443"
echo ""
echo "For PostgreSQL setup:"
echo "1. Install PostgreSQL"
echo "2. Create database: createdb lightning_auth_example"
echo "3. Update DATABASE_URL in .env.local"
echo "4. Copy prisma/schema.postgresql.prisma to prisma/schema.prisma"
echo "5. Run: npm run db:generate && npm run db:migrate"
echo ""
echo "Happy coding! ⚡"
