#!/bin/bash

# Fix Requirement Processor Migration Issue
# This script fixes the schema_migrations constraint issue

set -e

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

log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] WARNING:${NC} $1"
}

error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1"
}

# Database connection settings
DB_HOST=${DB_HOST:-"localhost"}
DB_PORT=${DB_PORT:-"5432"}
DB_USER=${DB_USER:-"postgres"}
DB_NAME=${DB_NAME:-"dev_pipeline"}
DB_PASSWORD=${DB_PASSWORD:-"password"}

log "🔧 Fixing Requirement Processor Migration Issue"
log "=============================================="

# Check if we're in the right directory
if [ ! -f "docker-compose.yml" ]; then
    error "Please run this script from the codenuk-backend-live directory"
    exit 1
fi

log "📋 Step 1: Stopping the requirement-processor service"
docker compose stop requirement-processor || true

log "📋 Step 2: Cleaning up failed migration records"
PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" << 'EOF'
-- Remove any failed migration records for requirement-processor
DELETE FROM schema_migrations WHERE service = 'requirement-processor' OR version LIKE '%.sql';

-- Ensure the schema_migrations table has the correct structure
ALTER TABLE schema_migrations ALTER COLUMN service SET NOT NULL;
EOF

log "📋 Step 3: Restarting the requirement-processor service"
docker compose up -d requirement-processor

log "📋 Step 4: Waiting for service to be healthy"
sleep 10

# Check if the service is running
if docker compose ps requirement-processor | grep -q "Up"; then
    log "✅ Requirement processor service is running"
else
    error "❌ Requirement processor service failed to start"
    docker compose logs requirement-processor
    exit 1
fi

log "📋 Step 5: Verifying migration status"
PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" << 'EOF'
-- Check migration status
SELECT service, version, applied_at, description 
FROM schema_migrations 
WHERE service = 'requirement-processor' 
ORDER BY applied_at;
EOF

log "✅ Migration fix completed!"
log "You can now restart the full deployment:"
log "docker compose up -d"
