#!/bin/bash

# Script to apply backup_jobs table migration to all library databases
# This should be run from the backend directory

set -e

# Use full docker path
DOCKER="/usr/local/bin/docker"

echo "Applying backup_jobs table migration..."

# Get database connection details from environment or use defaults
DB_HOST="${POSTGRES_HOST:-postgres}"
DB_PORT="${POSTGRES_PORT:-5432}"
DB_USER="${POSTGRES_USER:-storycove}"
DB_PASSWORD="${POSTGRES_PASSWORD:-password}"

# List of databases to update
DATABASES=("storycove" "storycove_afterdark")

for DB_NAME in "${DATABASES[@]}"; do
    echo ""
    echo "Applying migration to database: $DB_NAME"

    # Check if database exists
    if $DOCKER exec storycove-postgres-1 psql -U "$DB_USER" -lqt | cut -d \| -f 1 | grep -qw "$DB_NAME"; then
        echo "Database $DB_NAME exists, applying migration..."

        # Apply migration
        $DOCKER exec -i storycove-postgres-1 psql -U "$DB_USER" -d "$DB_NAME" < create_backup_jobs_table.sql

        if [ $? -eq 0 ]; then
            echo "✓ Migration applied successfully to $DB_NAME"
        else
            echo "✗ Failed to apply migration to $DB_NAME"
            exit 1
        fi
    else
        echo "⚠ Database $DB_NAME does not exist, skipping..."
    fi
done

echo ""
echo "Migration complete!"
echo ""
echo "Verifying table creation..."
for DB_NAME in "${DATABASES[@]}"; do
    if $DOCKER exec storycove-postgres-1 psql -U "$DB_USER" -lqt | cut -d \| -f 1 | grep -qw "$DB_NAME"; then
        echo ""
        echo "Checking $DB_NAME:"
        $DOCKER exec storycove-postgres-1 psql -U "$DB_USER" -d "$DB_NAME" -c "\d backup_jobs" 2>/dev/null || echo "  Table not found in $DB_NAME"
    fi
done
