#!/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 ata-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 if it doesn't exist
echo "📊 Creating unleash database if needed..."
docker exec ata-postgres psql -U postgres -tc "SELECT 1 FROM pg_database WHERE datname = 'unleash'" | grep -q 1 || \
docker exec ata-postgres psql -U postgres -c "CREATE DATABASE unleash;"
echo "✅ Unleash database ready"

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

echo "🎉 Database issues fixed!"
