#!/bin/bash

# Script para corregir el baseline de migraciones en bases de datos existentes
# Este script debe ejecutarse cuando Prisma no puede hacer baseline automático

set -e # Exit on any error

echo "🔧 Fixing Prisma Migration Baseline..."

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

# Check if running in project directory
if [ ! -f "docker-compose.yml" ]; then
    echo -e "${RED}❌ Error: docker-compose.yml not found.${NC}"
    echo -e "${YELLOW}Please run this script from the project root directory.${NC}"
    exit 1
fi

# Nombres de contenedores (debe coincidir con docker-compose.yml)
BACKEND_CONTAINER="ai-learning-platform-ewc-backend"

# Check if backend container is running
if ! docker ps --format '{{.Names}}' | grep -q "^${BACKEND_CONTAINER}$"; then
    echo -e "${RED}❌ Error: Backend container is not running.${NC}"
    echo -e "${YELLOW}Please start the application first: docker-compose --profile prod up -d${NC}"
    exit 1
fi

echo -e "${BLUE}📊 Checking current migration status...${NC}"
MIGRATION_STATUS=$(docker exec "$BACKEND_CONTAINER" npx prisma migrate status 2>&1 || echo "failed")

if echo "$MIGRATION_STATUS" | grep -q "Database schema is up to date"; then
    echo -e "${GREEN}✅ Database is already up to date${NC}"
    exit 0
fi

echo -e "${YELLOW}📋 Current migration status:${NC}"
echo "$MIGRATION_STATUS"
echo ""

# Check if we need baseline
if echo "$MIGRATION_STATUS" | grep -q "P3005\|baseline\|not empty"; then
    echo -e "${YELLOW}⚠️  Database needs baseline - marking existing migrations as applied...${NC}"
    
    # Get list of migrations that need to be resolved
    MIGRATIONS_TO_RESOLVE=$(echo "$MIGRATION_STATUS" | grep -o "202[0-9]*" | sort -u)
    
    if [ -n "$MIGRATIONS_TO_RESOLVE" ]; then
        echo -e "${BLUE}Migrations to mark as applied:${NC}"
        echo "$MIGRATIONS_TO_RESOLVE"
        echo ""
        
        # Confirm before proceeding
        read -p "Do you want to mark these migrations as applied? (yes/no): " -r
        if [[ ! $REPLY =~ ^[Yy][Ee][Ss]$ ]]; then
            echo -e "${YELLOW}Operation cancelled${NC}"
            exit 0
        fi
        
        echo -e "${BLUE}Marking migrations as applied...${NC}"
        for migration in $MIGRATIONS_TO_RESOLVE; do
            echo -e "${BLUE}  - Resolving migration: $migration${NC}"
            if docker exec "$BACKEND_CONTAINER" npx prisma migrate resolve --applied "$migration"; then
                echo -e "${GREEN}    ✅ Migration $migration marked as applied${NC}"
            else
                echo -e "${RED}    ❌ Failed to mark migration $migration as applied${NC}"
            fi
        done
        
        echo ""
        echo -e "${BLUE}Checking status after baseline...${NC}"
        docker exec "$BACKEND_CONTAINER" npx prisma migrate status
        
        echo ""
        echo -e "${BLUE}Deploying any remaining migrations...${NC}"
        if docker exec "$BACKEND_CONTAINER" npx prisma migrate deploy; then
            echo -e "${GREEN}✅ All migrations applied successfully${NC}"
        else
            echo -e "${YELLOW}⚠️  Some migrations may still be pending${NC}"
        fi
        
    else
        echo -e "${YELLOW}⚠️  Could not determine which migrations to resolve${NC}"
        echo -e "${BLUE}You may need to resolve migrations manually:${NC}"
        echo -e "  docker exec ${BACKEND_CONTAINER} npx prisma migrate resolve --applied <migration_name>"
    fi
    
else
    echo -e "${YELLOW}⚠️  No baseline needed, trying standard migration...${NC}"
    if docker exec "$BACKEND_CONTAINER" npx prisma migrate deploy; then
        echo -e "${GREEN}✅ Migrations applied successfully${NC}"
    else
        echo -e "${RED}❌ Migration failed${NC}"
        echo -e "${YELLOW}Check the logs: docker logs ${BACKEND_CONTAINER}${NC}"
        exit 1
    fi
fi

echo ""
echo -e "${GREEN}✅ Migration baseline fix completed${NC}"
echo -e "${BLUE}Final status:${NC}"
docker exec "$BACKEND_CONTAINER" npx prisma migrate status
