#!/bin/bash

echo "🚀 Starting database reset and seed process..."

# Default to development if no argument is passed
ENVIRONMENT=${1:-development}
ENVIRONMENT=$(echo "$ENVIRONMENT" | xargs)

# Set env file path based on environment
ENV_FILE=".env.${ENVIRONMENT}"

# Check if the env file exists
if [ ! -f "$ENV_FILE" ]; then
  echo "❌ Environment file '$ENV_FILE' not found!"
  exit 1
fi

echo "✅ Using environment file: $ENV_FILE"

# Clean CRLF line endings from the env file (in case it was edited on Windows)
sed -i 's/\r$//' "$ENV_FILE"

# Load environment variables from the file
set -a
source "$ENV_FILE"
set +a

# Validate essential variables
if [ -z "$DATABASE_HOST" ] || [ -z "$DATABASE_PORT" ] || [ -z "$DATABASE_USER" ] || [ -z "$DATABASE_PASSWORD" ] || [ -z "$DATABASE_NAME" ]; then
  echo "❌ One or more database environment variables are not set correctly in $ENV_FILE"
  exit 1
fi

# Create the PostgreSQL connection string
DATABASE_URL="postgresql://$DATABASE_USER:$DATABASE_PASSWORD@$DATABASE_HOST:$DATABASE_PORT/$DATABASE_NAME"

echo "🔄 Truncating all tables except 'child_processes' and resetting sequences..."

# Truncate all tables except child_processes and reset sequences
psql "$DATABASE_URL" <<'EOF'
DO $$
DECLARE
    r RECORD;
BEGIN
    FOR r IN (
        SELECT tablename 
        FROM pg_tables 
        WHERE schemaname = 'public' AND tablename != 'child_processes'
    ) LOOP
        EXECUTE 'TRUNCATE TABLE ' || quote_ident(r.tablename) || ' CASCADE;';
    END LOOP;

    FOR r IN (
        SELECT sequence_name 
        FROM information_schema.sequences 
        WHERE sequence_schema = 'public'
    ) LOOP
        EXECUTE 'ALTER SEQUENCE ' || quote_ident(r.sequence_name) || ' RESTART WITH 1;';
    END LOOP;
END
$$;
EOF

if [ $? -ne 0 ]; then
  echo "❌ Failed to truncate tables or reset sequences."
  exit 1
fi

# Run seed script based on NODE_ENV
echo "🌱 Running seed script for NODE_ENV=$ENVIRONMENT"

case "$ENVIRONMENT" in
  development)
    npm run dev:seed:pg
    ;;
  staging)
    npm run stag:seed:pg
    ;;
  production)
    npm run prod:seed:pg
    ;;
  *)
    echo "❌ Unknown NODE_ENV: $NODE_ENV"
    exit 1
    ;;
esac

echo "✅ Database reset and seed process completed."
