#!/bin/bash

# Master Migration Script for ParentFlow App
# This script runs all database migrations in the correct order for fresh installations
# Created: October 6, 2025

set -e  # Exit on any error

# Configuration
DATABASE_NAME="${DATABASE_NAME:-parentflow_production}"
DATABASE_USER="${DATABASE_USER:-parentflow_user}"
DATABASE_PASSWORD="${DATABASE_PASSWORD:-parentflow_secure_password_2024}"
DATABASE_HOST="${DATABASE_HOST:-localhost}"
DATABASE_PORT="${DATABASE_PORT:-5432}"

# For development
if [ "$NODE_ENV" = "development" ]; then
    DATABASE_NAME="${DATABASE_NAME:-maternal_app}"
    DATABASE_USER="${DATABASE_USER:-maternal_user}"
    DATABASE_PASSWORD="${DATABASE_PASSWORD:-maternal_dev_password_2024}"
    DATABASE_PORT="${DATABASE_PORT:-5555}"
fi

MIGRATION_DIR="$(dirname "$0")/../src/database/migrations"

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function to run a migration
run_migration() {
    local migration_file=$1
    local migration_name=$(basename "$migration_file")

    echo -e "${YELLOW}Running migration: $migration_name${NC}"

    PGPASSWORD="$DATABASE_PASSWORD" psql \
        -h "$DATABASE_HOST" \
        -p "$DATABASE_PORT" \
        -U "$DATABASE_USER" \
        -d "$DATABASE_NAME" \
        -f "$migration_file" \
        --quiet

    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ Migration $migration_name completed${NC}"
        return 0
    else
        echo -e "${RED}✗ Migration $migration_name failed!${NC}"
        return 1
    fi
}

# Array of migrations in correct order (with current duplicate names)
# These will be renamed in the next step
MIGRATIONS=(
    "V001_create_core_auth.sql"
    "V002_create_family_structure.sql"
    "V003_create_refresh_tokens.sql"
    "V004_create_activity_tracking.sql"
    "V005_add_user_preferences.sql"
    "V006_create_audit_log.sql"
    "V007_create_notifications.sql"
    "V008_create_photos.sql"                      # First V008
    "V008_add_user_photo_url.sql"                 # Second V008 (will be V009)
    "V009_add_photo_alt_text.sql"                 # First V009 (will be V010)
    "V008_add_eula_acceptance.sql"                # Third V008 (will be V011)
    "V010_add_mfa_fields.sql"                     # First V010 (will be V012)
    "V011_add_webauthn_credentials.sql"           # First V011 (will be V013)
    "V011_create_password_reset_tokens.sql"       # Second V011 (will be V014)
    "V010_create_ai_conversations.sql"            # Second V010 (will be V015)
    "V012_create_voice_feedback.sql"              # V012 (will be V016)
    "V014_create_conversation_embeddings.sql"     # V014 (will be V017)
    "V008_create_data_deletion_requests.sql"      # Fourth V008 (will be V018)
    "V015_create_deletion_requests.sql"           # V015 (will be V019)
    "V016_add_coppa_compliance.sql"               # V016 (will be V020)
    "V009_create_activity_partitions.sql"         # Second V009 (will be V021)
    "V009_add_performance_indexes.sql"            # Third V009 (will be V022)
    "V010_create_user_preferences.sql"            # Third V010 (will be V023)
    "V013_add_medicine_activity_types.sql"        # V013 (will be V024)
    "V017_add_child_display_preferences.sql"      # V017 (will be V025)
    "V018_create_multi_child_preferences.sql"     # V018 (will be V026)
    "V019_add_activity_bulk_operations.sql"       # V019 (will be V027)
)

echo "=========================================="
echo "ParentFlow Database Migration Script"
echo "=========================================="
echo "Database: $DATABASE_NAME@$DATABASE_HOST:$DATABASE_PORT"
echo "User: $DATABASE_USER"
echo "Total migrations to run: ${#MIGRATIONS[@]}"
echo "=========================================="

# Check if database exists
echo -e "${YELLOW}Checking database connection...${NC}"
PGPASSWORD="$DATABASE_PASSWORD" psql \
    -h "$DATABASE_HOST" \
    -p "$DATABASE_PORT" \
    -U "$DATABASE_USER" \
    -d "$DATABASE_NAME" \
    -c "SELECT version();" > /dev/null 2>&1

if [ $? -ne 0 ]; then
    echo -e "${RED}ERROR: Cannot connect to database!${NC}"
    echo "Please ensure:"
    echo "  1. PostgreSQL is running"
    echo "  2. Database '$DATABASE_NAME' exists"
    echo "  3. User '$DATABASE_USER' has access"
    echo "  4. Password is correct"
    exit 1
fi

echo -e "${GREEN}✓ Database connection successful${NC}"
echo ""

# Ask for confirmation
read -p "Do you want to proceed with the migrations? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Migration cancelled."
    exit 0
fi

echo ""
echo "Starting migrations..."
echo "=========================================="

# Counter for successful migrations
SUCCESS_COUNT=0
FAILED_COUNT=0

# Run each migration
for migration in "${MIGRATIONS[@]}"; do
    migration_path="$MIGRATION_DIR/$migration"

    if [ ! -f "$migration_path" ]; then
        echo -e "${YELLOW}Warning: Migration file not found: $migration${NC}"
        echo "Skipping..."
        continue
    fi

    if run_migration "$migration_path"; then
        ((SUCCESS_COUNT++))
    else
        ((FAILED_COUNT++))
        echo -e "${RED}Migration failed. Stopping execution.${NC}"
        break
    fi

    # Small delay between migrations
    sleep 0.5
done

echo ""
echo "=========================================="
echo "Migration Summary"
echo "=========================================="
echo -e "${GREEN}Successful: $SUCCESS_COUNT${NC}"
echo -e "${RED}Failed: $FAILED_COUNT${NC}"

if [ $FAILED_COUNT -eq 0 ]; then
    echo -e "${GREEN}✓ All migrations completed successfully!${NC}"
    exit 0
else
    echo -e "${RED}✗ Migration process failed. Please check the errors above.${NC}"
    exit 1
fi