#!/bin/bash

# Fix PostgreSQL user creation for existing deployments
# This script creates the pipeline_admin user in an existing PostgreSQL container

echo "🔧 Fixing PostgreSQL user authentication..."

# Wait for PostgreSQL to be ready
echo "⏳ Waiting for PostgreSQL to be ready..."
until docker exec pipeline_postgres pg_isready -U postgres > /dev/null 2>&1; do
    echo "   PostgreSQL is not ready yet, waiting..."
    sleep 2
done

echo "✅ PostgreSQL is ready"

# Execute the user creation script
echo "👤 Creating pipeline_admin user..."
docker exec -i pipeline_postgres psql -U postgres -d postgres < ./databases/scripts/create-pipeline-admin.sql

if [ $? -eq 0 ]; then
    echo "✅ Pipeline admin user created successfully"
    echo "🚀 You can now restart the migrations service:"
    echo "   docker compose restart migrations"
else
    echo "❌ Failed to create pipeline admin user"
    exit 1
fi
