#!/bin/bash
# Quick setup that handles database creation and password setup

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
API_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

cd "$API_DIR"

echo "=========================================="
echo "Sovereign Stack - Quick Setup"
echo "=========================================="
echo ""

# Step 1: Ensure .env exists
if [ ! -f .env ]; then
  echo "Creating .env file..."
  cp .env.example .env 2>/dev/null || {
    cat > .env << 'EOF'
DB_HOST=localhost
DB_PORT=5432
DB_NAME=sankofa
DB_USER=postgres
DB_PASSWORD=
NODE_ENV=development
PORT=4000
EOF
  }
fi

# Step 2: Check if database exists, create if not
echo "Checking database..."
DB_EXISTS=$(sudo -u postgres psql -lqt 2>/dev/null | cut -d \| -f 1 | grep -w sankofa | wc -l)

if [ "$DB_EXISTS" -eq 0 ]; then
  echo "Database 'sankofa' not found. Creating..."
  sudo -u postgres createdb sankofa 2>/dev/null && echo "✅ Database created" || {
    echo "⚠ Could not create database automatically."
    echo "Please run manually: sudo -u postgres createdb sankofa"
  }
else
  echo "✅ Database 'sankofa' exists"
fi

# Step 3: Get database password
CURRENT_PASS=$(grep "^DB_PASSWORD=" .env 2>/dev/null | cut -d'=' -f2- | tr -d '"' | tr -d "'" | xargs)

if [ -z "$CURRENT_PASS" ] || [ "$CURRENT_PASS" = "your_secure_password_here" ] || [ "$CURRENT_PASS" = "YOUR_ACTUAL_DATABASE_PASSWORD_HERE" ]; then
  echo ""
  echo "Database password needed."
  echo ""
  echo "Options:"
  echo "  1. Enter your PostgreSQL password"
  echo "  2. Set a new password for postgres user (recommended for development)"
  echo ""
  read -p "Choose option (1 or 2): " OPTION
  
  if [ "$OPTION" = "2" ]; then
    echo ""
    echo "Setting new password for postgres user..."
    read -sp "Enter new password (min 8 chars): " NEW_PASS
    echo ""
    sudo -u postgres psql -c "ALTER USER postgres PASSWORD '$NEW_PASS';" 2>/dev/null && {
      sed -i "s|^DB_PASSWORD=.*|DB_PASSWORD=$NEW_PASS|" .env
      echo "✅ Password set and .env updated"
    } || {
      echo "❌ Failed to set password. Please set manually."
      exit 1
    }
  else
    echo ""
    read -sp "Enter PostgreSQL password: " DB_PASS
    echo ""
    sed -i "s|^DB_PASSWORD=.*|DB_PASSWORD=$DB_PASS|" .env
    echo "✅ Password updated in .env"
  fi
fi

# Ensure NODE_ENV is development
if ! grep -q "^NODE_ENV=development" .env; then
  sed -i 's/^NODE_ENV=.*/NODE_ENV=development/' .env || echo "NODE_ENV=development" >> .env
fi

# Step 4: Test connection
echo ""
echo "Testing database connection..."
DB_PASS=$(grep "^DB_PASSWORD=" .env | cut -d'=' -f2- | tr -d '"' | tr -d "'" | xargs)
if PGPASSWORD="$DB_PASS" psql -h localhost -U postgres -d sankofa -c "SELECT 1;" >/dev/null 2>&1; then
  echo "✅ Database connection successful"
else
  echo "❌ Database connection failed"
  echo ""
  echo "Please verify:"
  echo "  1. PostgreSQL is running: sudo systemctl status postgresql"
  echo "  2. Password is correct in .env"
  echo "  3. Database exists: sudo -u postgres psql -l | grep sankofa"
  echo ""
  echo "You can reset the postgres password with:"
  echo "  sudo -u postgres psql -c \"ALTER USER postgres PASSWORD 'your_password';\""
  exit 1
fi

# Step 5: Run migrations
echo ""
echo "Step 1: Running database migrations..."
echo "----------------------------------------"
pnpm db:migrate:up || {
  echo "❌ Migration failed"
  exit 1
}
echo "✅ Migrations completed"

# Step 6: Seed services
echo ""
echo "Step 2: Seeding Sovereign Stack services..."
echo "----------------------------------------"
pnpm db:seed:sovereign-stack || {
  echo "❌ Seeding failed"
  exit 1
}
echo "✅ Services seeded"

# Step 7: Verify
echo ""
echo "Step 3: Verifying setup..."
echo "----------------------------------------"
pnpm verify:sovereign-stack || {
  echo "⚠ Verification found issues"
  exit 1
}

echo ""
echo "=========================================="
echo "✅ Sovereign Stack setup complete!"
echo "=========================================="
