#!/bin/bash

# Fix Database Issues Script
# Handles common database setup issues discovered during deployment

set -e

echo "🔧 Fixing database issues..."

# Wait for PostgreSQL to be ready
echo "⏳ Waiting for PostgreSQL to be ready..."
timeout=60
counter=0
while ! docker exec apa-postgres pg_isready -U postgres >/dev/null 2>&1; do
    if [ $counter -ge $timeout ]; then
        echo "❌ PostgreSQL failed to start within $timeout seconds"
        exit 1
    fi
    sleep 1
    counter=$((counter + 1))
done
echo "✅ PostgreSQL is ready"

# Create unleash database and user if they don't exist
echo "📊 Creating unleash database and user if needed..."
docker exec apa-postgres psql -U postgres -d template1 -tc "SELECT 1 FROM pg_database WHERE datname = 'unleash'" | grep -q 1 || \
docker exec apa-postgres psql -U postgres -d template1 -c "CREATE DATABASE unleash;"
docker exec apa-postgres psql -U postgres -d template1 -tc "SELECT 1 FROM pg_user WHERE usename = 'unleash'" | grep -q 1 || \
docker exec apa-postgres psql -U postgres -d template1 -c "CREATE USER unleash WITH PASSWORD 'unleash';"
docker exec apa-postgres psql -U postgres -d template1 -c "GRANT ALL PRIVILEGES ON DATABASE unleash TO unleash;"
echo "✅ Unleash database and user ready"

# Create tax_system database for Authentik if needed
echo "🔐 Creating tax_system database for Authentik if needed..."
docker exec apa-postgres psql -U postgres -d template1 -tc "SELECT 1 FROM pg_database WHERE datname = 'tax_system'" | grep -q 1 || \
docker exec apa-postgres psql -U postgres -d template1 -c "CREATE DATABASE tax_system;"
docker exec apa-postgres psql -U postgres -d template1 -tc "SELECT 1 FROM pg_database WHERE datname = 'authentik'" | grep -q 1 || \
docker exec apa-postgres psql -U postgres -d template1 -c "CREATE DATABASE authentik;"
echo "✅ Authentik database ready"

# Create authentik user if it doesn't exist
echo "🔐 Creating authentik user if needed..."
docker exec apa-postgres psql -U postgres -d template1 -tc "SELECT 1 FROM pg_user WHERE usename = 'authentik'" | grep -q 1 || \
docker exec apa-postgres psql -U postgres -d template1 -c "CREATE USER authentik WITH PASSWORD 'authentik';"
docker exec apa-postgres psql -U postgres -d template1 -c "GRANT ALL PRIVILEGES ON DATABASE tax_system TO authentik;"
docker exec apa-postgres psql -U postgres -d template1 -c "GRANT ALL PRIVILEGES ON DATABASE authentik TO authentik;"
echo "✅ Authentik user ready"

echo "🎉 Database issues fixed!"
