#!/bin/bash
# Setup script for Sovereign Stack marketplace services
# This script runs migrations and seeds the marketplace

set -e

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

cd "$API_DIR"

echo "=========================================="
echo "Sovereign Stack Marketplace Setup"
echo "=========================================="
echo ""
echo "This script will:"
echo "  1. Run database migrations (adds new categories)"
echo "  2. Seed all 9 Sovereign Stack services"
echo "  3. Verify the setup"
echo ""

# Check if .env exists
if [ ! -f .env ]; then
  echo "⚠ Warning: .env file not found."
  echo ""
  echo "Would you like to create one from .env.example? (y/N)"
  read -p "> " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    if [ -f .env.example ]; then
      ./scripts/create-env.sh
      echo ""
      echo "⚠ Please edit .env and set your database password before continuing."
      echo "Press Enter when ready, or Ctrl+C to exit..."
      read
    else
      echo "❌ .env.example not found. Please create .env manually."
      exit 1
    fi
  else
    echo ""
    echo "Please create a .env file with the following variables:"
    echo "  DB_HOST=localhost"
    echo "  DB_PORT=5432"
    echo "  DB_NAME=sankofa"
    echo "  DB_USER=postgres"
    echo "  DB_PASSWORD=your_password_here"
    echo ""
    echo "For development, DB_PASSWORD must be at least 8 characters."
    echo "For production, DB_PASSWORD must be at least 32 characters with uppercase, lowercase, numbers, and special characters."
    echo ""
    read -p "Press Enter when .env is ready, or Ctrl+C to exit..."
  fi
fi

# Step 1: Run migrations
echo "Step 1: Running database migrations..."
echo "----------------------------------------"
pnpm db:migrate:up || {
  echo "❌ Migration failed. Please check database connection and try again."
  exit 1
}
echo "✅ Migrations completed"
echo ""

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

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

echo "=========================================="
echo "✅ Sovereign Stack setup complete!"
echo "=========================================="
echo ""
echo "Next steps:"
echo "1. Access the marketplace at: https://portal.sankofa.nexus/marketplace"
echo "2. Browse Phoenix Cloud Services offerings"
echo "3. Subscribe to services as needed"
echo ""
