#!/bin/bash

# Script to check and create databases based on README requirements
# This script checks for punimtag and punimtag_auth databases and creates them if needed

set -e

echo "🔍 Checking databases..."
echo ""

# Load .env file if it exists
if [ -f .env ]; then
    export $(grep -v '^#' .env | xargs)
fi

# Try to extract connection info from DATABASE_URL or use defaults
# Format: postgresql://user:password@host:port/database
if [ -n "$DATABASE_URL" ]; then
    # Extract connection details from DATABASE_URL
    DB_URL="$DATABASE_URL"
    # Remove postgresql:// prefix
    DB_URL="${DB_URL#postgresql://}"
    # Extract user:password@host:port/database
    if [[ "$DB_URL" =~ ^([^:]+):([^@]+)@([^:]+):([^/]+)/(.+)$ ]]; then
        PGUSER="${BASH_REMATCH[1]}"
        PGPASSWORD="${BASH_REMATCH[2]}"
        PGHOST="${BASH_REMATCH[3]}"
        PGPORT="${BASH_REMATCH[4]}"
    elif [[ "$DB_URL" =~ ^([^@]+)@([^:]+):([^/]+)/(.+)$ ]]; then
        PGUSER="${BASH_REMATCH[1]}"
        PGHOST="${BASH_REMATCH[2]}"
        PGPORT="${BASH_REMATCH[3]}"
    elif [[ "$DB_URL" =~ ^([^@]+)@([^/]+)/(.+)$ ]]; then
        PGUSER="${BASH_REMATCH[1]}"
        PGHOST="${BASH_REMATCH[2]}"
        PGPORT="5432"
    fi
fi

# For database creation, we need a superuser
# Try to use postgres user, or allow override via POSTGRES_SUPERUSER env var
SUPERUSER=${POSTGRES_SUPERUSER:-postgres}
SUPERUSER_PASSWORD=${POSTGRES_SUPERUSER_PASSWORD:-}

# Use defaults if not set
PGUSER=${PGUSER:-postgres}
PGHOST=${PGHOST:-localhost}
PGPORT=${PGPORT:-5432}

# Export password if set
if [ -n "$PGPASSWORD" ]; then
    export PGPASSWORD
fi

# For superuser operations, use separate password if provided
if [ -n "$SUPERUSER_PASSWORD" ]; then
    export PGPASSWORD="$SUPERUSER_PASSWORD"
    ADMIN_USER="$SUPERUSER"
else
    # Try to use the same user/password, or prompt
    ADMIN_USER="$SUPERUSER"
fi

# Check if punimtag database exists
echo "Checking punimtag database..."
if psql -h "$PGHOST" -p "$PGPORT" -U "$ADMIN_USER" -d postgres -lqt 2>/dev/null | cut -d \| -f 1 | grep -qw punimtag; then
    echo "✅ punimtag database exists"
else
    echo "⚠️  punimtag database does not exist"
    echo "   This is the main database with photos - it should already exist."
    echo "   If you need to create it, please do so manually or ensure your PunimTag setup is complete."
fi

echo ""

# Check if punimtag_auth database exists
echo "Checking punimtag_auth database..."
if psql -h "$PGHOST" -p "$PGPORT" -U "$ADMIN_USER" -d postgres -lqt 2>/dev/null | cut -d \| -f 1 | grep -qw punimtag_auth; then
    echo "✅ punimtag_auth database exists"
    AUTH_DB_EXISTS=true
else
    echo "📦 Creating punimtag_auth database..."
    echo "   (This requires a PostgreSQL superuser - using: $ADMIN_USER)"
    psql -h "$PGHOST" -p "$PGPORT" -U "$ADMIN_USER" -d postgres -c "CREATE DATABASE punimtag_auth;" 2>&1
    if [ $? -eq 0 ]; then
        echo "✅ punimtag_auth database created"
        AUTH_DB_EXISTS=true
    else
        echo "❌ Failed to create punimtag_auth database"
        echo "   You may need to run this as a PostgreSQL superuser:"
        echo "   sudo -u postgres psql -c 'CREATE DATABASE punimtag_auth;'"
        exit 1
    fi
fi

echo ""

# Now check and create tables in punimtag_auth
if [ "$AUTH_DB_EXISTS" = true ]; then
    echo "🔍 Checking tables in punimtag_auth..."
    
    # Check if users table exists
    if psql -h "$PGHOST" -p "$PGPORT" -U "$ADMIN_USER" -d punimtag_auth -c "\dt users" 2>/dev/null | grep -q "users"; then
        echo "✅ Tables already exist in punimtag_auth"
    else
        echo "📋 Creating tables in punimtag_auth..."
        
        # Create tables using create_auth_tables.sql
        if [ -f "create_auth_tables.sql" ]; then
            echo "   Running create_auth_tables.sql..."
            psql -h "$PGHOST" -p "$PGPORT" -U "$ADMIN_USER" -d punimtag_auth -f create_auth_tables.sql 2>&1
        else
            echo "   ⚠️  create_auth_tables.sql not found, creating tables manually..."
            psql -h "$PGHOST" -p "$PGPORT" -U "$ADMIN_USER" -d punimtag_auth <<EOF
CREATE TABLE IF NOT EXISTS users (
    id SERIAL PRIMARY KEY,
    email VARCHAR(255) UNIQUE NOT NULL,
    name VARCHAR(255),
    password_hash VARCHAR(255) NOT NULL,
    is_admin BOOLEAN DEFAULT FALSE,
    has_write_access BOOLEAN DEFAULT FALSE,
    email_verified BOOLEAN DEFAULT FALSE,
    email_confirmation_token VARCHAR(255) UNIQUE,
    email_confirmation_token_expiry TIMESTAMP,
    password_reset_token VARCHAR(255) UNIQUE,
    password_reset_token_expiry TIMESTAMP,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS pending_identifications (
    id SERIAL PRIMARY KEY,
    face_id INTEGER NOT NULL,
    user_id INTEGER NOT NULL,
    first_name VARCHAR(255) NOT NULL,
    last_name VARCHAR(255) NOT NULL,
    middle_name VARCHAR(255),
    maiden_name VARCHAR(255),
    date_of_birth DATE,
    status VARCHAR(50) DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_pending_identifications_face_id ON pending_identifications(face_id);
CREATE INDEX IF NOT EXISTS idx_pending_identifications_user_id ON pending_identifications(user_id);
CREATE INDEX IF NOT EXISTS idx_pending_identifications_status ON pending_identifications(status);
EOF
        fi
        
        echo "✅ Tables created"
    fi
    
    echo ""
    echo "🔍 Checking for required migrations..."
    
    # Check pending_photos table
    if psql -h "$PGHOST" -p "$PGPORT" -U "$ADMIN_USER" -d punimtag_auth -c "\dt pending_photos" 2>/dev/null | grep -q "pending_photos"; then
        echo "✅ pending_photos table exists"
    else
        echo "📋 Creating pending_photos table..."
        if [ -f "migrations/add-pending-photos-table.sql" ]; then
            psql -h "$PGHOST" -p "$PGPORT" -U "$ADMIN_USER" -d punimtag_auth -f migrations/add-pending-photos-table.sql 2>&1
            echo "✅ pending_photos table created"
        else
            echo "   ⚠️  Migration file not found, skipping..."
        fi
    fi
    
    # Check email verification columns
    if psql -h "$PGHOST" -p "$PGPORT" -U "$ADMIN_USER" -d punimtag_auth -c "\d users" 2>/dev/null | grep -q "email_verified"; then
        echo "✅ Email verification columns exist"
    else
        echo "📋 Adding email verification columns..."
        if [ -f "migrations/add-email-verification-columns.sql" ]; then
            psql -h "$PGHOST" -p "$PGPORT" -U "$ADMIN_USER" -d punimtag_auth -f migrations/add-email-verification-columns.sql 2>&1
            echo "✅ Email verification columns added"
        else
            echo "   ⚠️  Migration file not found, skipping..."
        fi
    fi
fi

echo ""
echo "🎉 Database setup complete!"
echo ""
echo "Note: If you encountered permission errors, you may need to run this script"
echo "      with a PostgreSQL superuser. You can set:"
echo "      POSTGRES_SUPERUSER=postgres POSTGRES_SUPERUSER_PASSWORD=yourpassword ./scripts/check-and-create-databases.sh"
echo ""
echo "Next steps:"
echo "1. Ensure your .env file has correct DATABASE_URL and DATABASE_URL_AUTH"
echo "2. Run: npm run prisma:generate:all"
echo "3. Create admin user: npx tsx scripts/create-admin-user.ts"

