#!/usr/bin/env bash

set -euo pipefail

# ========================================
# DATABASE CLEANUP SCRIPT
# ========================================

# Database connection parameters
DB_HOST=${POSTGRES_HOST:-postgres}
DB_PORT=${POSTGRES_PORT:-5432}
DB_NAME=${POSTGRES_DB:-dev_pipeline}
DB_USER=${POSTGRES_USER:-pipeline_admin}
DB_PASSWORD=${POSTGRES_PASSWORD:-secure_pipeline_2024}

# Log function with timestamp
log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"
}

log "🧹 Starting database cleanup..."

# Connect to PostgreSQL and clean up unwanted tables
PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" << 'EOF'
-- List all tables before cleanup
\echo '📋 Tables before cleanup:'
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_name;

-- Drop unwanted/duplicate tables that might have been created
\echo '🗑️  Dropping unwanted tables...'

-- Drop tables that might be duplicates or unwanted
DROP TABLE IF EXISTS user_api_keys CASCADE;
DROP TABLE IF EXISTS role_scope CASCADE;
DROP TABLE IF EXISTS scope CASCADE;
DROP TABLE IF EXISTS service_health CASCADE;
DROP TABLE IF EXISTS settings CASCADE;
DROP TABLE IF EXISTS shared_credentials CASCADE;
DROP TABLE IF EXISTS shared_workflow CASCADE;
DROP TABLE IF EXISTS stack_recommendations CASCADE;
DROP TABLE IF EXISTS system_architectures CASCADE;
DROP TABLE IF EXISTS tag_entity CASCADE;
DROP TABLE IF EXISTS tech_pricing CASCADE;
DROP TABLE IF EXISTS tech_stack_decisions CASCADE;
DROP TABLE IF EXISTS template_features CASCADE;
DROP TABLE IF EXISTS templates CASCADE;
DROP TABLE IF EXISTS test_case_execution CASCADE;
DROP TABLE IF EXISTS test_results CASCADE;
DROP TABLE IF EXISTS test_run CASCADE;
DROP TABLE IF EXISTS testing_technologies CASCADE;
DROP TABLE IF EXISTS tools CASCADE;
DROP TABLE IF EXISTS "user" CASCADE;
DROP TABLE IF EXISTS user_feature_preferences CASCADE;
DROP TABLE IF EXISTS user_preferences CASCADE;
DROP TABLE IF EXISTS user_projects CASCADE;
DROP TABLE IF EXISTS user_sessions CASCADE;
DROP TABLE IF EXISTS variables CASCADE;
DROP TABLE IF EXISTS webhook_entity CASCADE;
DROP TABLE IF EXISTS wireframe_elements CASCADE;
DROP TABLE IF EXISTS wireframe_versions CASCADE;
DROP TABLE IF EXISTS wireframes CASCADE;
DROP TABLE IF EXISTS workflow_entity CASCADE;
DROP TABLE IF EXISTS workflow_history CASCADE;
DROP TABLE IF EXISTS workflow_statistics CASCADE;
DROP TABLE IF EXISTS workflows_tags CASCADE;

-- Drop any duplicate functions
DROP FUNCTION IF EXISTS update_updated_at_column() CASCADE;

-- Clean up any orphaned sequences
DO $$
DECLARE
    seq_record RECORD;
BEGIN
    FOR seq_record IN 
        SELECT sequence_name 
        FROM information_schema.sequences 
        WHERE sequence_schema = 'public'
        AND sequence_name NOT IN (
            SELECT column_default 
            FROM information_schema.columns 
            WHERE table_schema = 'public' 
            AND column_default LIKE 'nextval%'
        )
    LOOP
        EXECUTE 'DROP SEQUENCE IF EXISTS ' || seq_record.sequence_name || ' CASCADE';
    END LOOP;
END $$;

-- List tables after cleanup
\echo '📋 Tables after cleanup:'
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_name;

\echo '✅ Database cleanup completed!'
EOF

if [ $? -eq 0 ]; then
  log "✅ Database cleanup completed successfully"
else
  log "❌ Database cleanup failed"
  exit 1
fi
