#!/bin/bash
set -e

echo "=== Monaco USA Portal - Migration Runner ==="

# Wait for database to be ready
echo "Waiting for database..."
retries=30
while [ $retries -gt 0 ]; do
  if pg_isready -h "$PGHOST" -U "$PGUSER" > /dev/null 2>&1; then
    echo "Database is ready."
    break
  fi
  retries=$((retries - 1))
  sleep 2
done

if [ $retries -eq 0 ]; then
  echo "ERROR: Database did not become ready in time"
  exit 1
fi

# Wait for storage-api to create its tables (it starts after db)
echo "Waiting for storage-api to create tables..."
storage_retries=30
while [ $storage_retries -gt 0 ]; do
  has_table=$(psql -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -tAc \
    "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'storage' AND table_name = 'objects'" 2>/dev/null || echo "0")
  if [ "$has_table" = "1" ]; then
    echo "Storage tables found."
    break
  fi
  storage_retries=$((storage_retries - 1))
  sleep 2
done

if [ $storage_retries -eq 0 ]; then
  echo "WARNING: storage.objects table not found after 60s - storage policies will be skipped in post-deploy"
fi

# Detect fresh vs existing database
has_members=$(psql -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -tAc \
  "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'members'" 2>/dev/null || echo "0")

if [ "$has_members" = "0" ]; then
  echo "=== Fresh database detected - running init.sql ==="
  psql -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -f /sql/init.sql
  echo "=== init.sql completed ==="
else
  echo "=== Existing database detected - skipping init.sql ==="
fi

# Always run post-deploy (idempotent)
echo "=== Running post-deploy.sql ==="
psql -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -f /sql/post-deploy.sql
echo "=== post-deploy.sql completed ==="

echo "=== Migration runner finished successfully ==="
