#!/bin/bash
# Fix Docker Database Configuration
# Ensures database and user are properly configured

set -e

echo "========================================="
echo "Fixing Docker Database Configuration"
echo "========================================="
echo ""

cd "$(dirname "$0")/.."

# Check if Docker Compose services are running
echo "Step 1: Checking Docker services..."
if ! docker compose -f docker/docker-compose.as4.yml ps postgres | grep -q "Up"; then
    echo "   Starting PostgreSQL service..."
    cd docker
    docker compose -f docker-compose.as4.yml up -d postgres
    cd ..
    sleep 5
else
    echo "   ✓ PostgreSQL service is running"
fi
echo ""

# Wait for PostgreSQL to be ready
echo "Step 2: Waiting for PostgreSQL to be ready..."
for i in {1..30}; do
    if docker compose -f docker/docker-compose.as4.yml exec -T postgres pg_isready -U postgres &> /dev/null; then
        echo "   ✓ PostgreSQL is ready"
        break
    fi
    if [ $i -eq 30 ]; then
        echo "   ✗ PostgreSQL failed to start"
        exit 1
    fi
    sleep 1
done
echo ""

# Note: Docker Compose uses POSTGRES_USER which creates a superuser with that name
# So dbis_user is already the superuser, we just need to ensure database exists

# Check if database exists
echo "Step 3: Ensuring database exists..."
DB_EXISTS=$(docker compose -f docker/docker-compose.as4.yml exec -T postgres psql -U dbis_user -tAc "SELECT 1 FROM pg_database WHERE datname='dbis_core';" 2>/dev/null || echo "0")
if [ "$DB_EXISTS" != "1" ]; then
    echo "   Creating database 'dbis_core'..."
    docker compose -f docker/docker-compose.as4.yml exec -T postgres psql -U dbis_user -c "CREATE DATABASE dbis_core;" 2>&1 || true
    echo "   ✓ Database created"
else
    echo "   ✓ Database already exists"
fi
echo ""

# Update password if needed (ensure it matches what's in docker-compose)
echo "Step 4: Ensuring user password is set..."
docker compose -f docker/docker-compose.as4.yml exec -T postgres psql -U dbis_user -c "ALTER USER dbis_user WITH PASSWORD 'dbis_password';" 2>&1 || true
echo "   ✓ Password configured"
echo ""

# Grant privileges
echo "Step 5: Granting privileges..."
docker compose -f docker/docker-compose.as4.yml exec -T postgres psql -U dbis_user -d dbis_core -c "GRANT ALL PRIVILEGES ON DATABASE dbis_core TO dbis_user;" 2>&1 || true
docker compose -f docker/docker-compose.as4.yml exec -T postgres psql -U dbis_user -c "ALTER USER dbis_user CREATEDB;" 2>&1 || true
echo "   ✓ Privileges granted"
echo ""

# Test connection
echo "Step 6: Testing connection..."
if docker compose -f docker/docker-compose.as4.yml exec -T postgres psql -U dbis_user -d dbis_core -c "SELECT version();" &> /dev/null; then
    PG_VERSION=$(docker compose -f docker/docker-compose.as4.yml exec -T postgres psql -U dbis_user -d dbis_core -c "SELECT version();" -t -A 2>/dev/null | head -1)
    echo "   ✓ Connection successful"
    echo "   PostgreSQL version: $PG_VERSION"
else
    echo "   ✗ Connection failed"
    exit 1
fi
echo ""

# Update .env if needed
echo "Step 7: Updating .env file..."
if [ -f .env ]; then
    # Update DATABASE_URL to use localhost Docker
    if ! grep -q "localhost:5432/dbis_core" .env || ! grep -q "dbis_user:dbis_password" .env; then
        echo "   Updating DATABASE_URL in .env..."
        # Backup .env
        cp .env .env.backup.$(date +%Y%m%d_%H%M%S)
        
        # Update or add DATABASE_URL
        if grep -q "^DATABASE_URL=" .env; then
            sed -i 's|^DATABASE_URL=.*|DATABASE_URL=postgresql://dbis_user:dbis_password@localhost:5432/dbis_core|' .env
        else
            echo "DATABASE_URL=postgresql://dbis_user:dbis_password@localhost:5432/dbis_core" >> .env
        fi
        echo "   ✓ .env updated"
    else
        echo "   ✓ DATABASE_URL already configured correctly"
    fi
else
    echo "   Creating .env file..."
    cat > .env <<EOF
# Database (Docker Compose)
DATABASE_URL=postgresql://dbis_user:dbis_password@localhost:5432/dbis_core

# Redis (Docker Compose)
REDIS_URL=redis://localhost:6379

# AS4 Configuration
AS4_BASE_URL=http://localhost:3000
AS4_LOG_LEVEL=debug
NODE_ENV=development
EOF
    echo "   ✓ .env file created"
fi
echo ""

echo "========================================="
echo "Database Configuration Fixed!"
echo "========================================="
echo ""
echo "Next steps:"
echo "1. Run migration: npx prisma migrate deploy"
echo "2. Seed marketplace: npx ts-node scripts/seed-as4-settlement-marketplace-offering.ts"
echo "3. Start server: npm run dev"
echo ""
