#!/bin/bash

# Exit on error
set -e

# Function to show usage
show_usage() {
    echo "Usage: $0 [-d|--database-url <database_url>] [-h|--help]"
    echo "Options:"
    echo "  -d, --database-url <url>    Specify the database URL (required)"
    echo "                              Format: postgresql://user:password@host:port/dbname"
    echo "  -h, --help                  Show this help message"
    echo
    echo "Example:"
    echo "  $0 -d postgresql://user:password@localhost:5432/dbname"
    exit 1
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -d|--database-url)
            DATABASE_URL="$2"
            shift 2
            ;;
        -h|--help)
            show_usage
            ;;
        *)
            echo "Unknown option: $1"
            show_usage
            ;;
    esac
done

# Check if DATABASE_URL is provided
if [ -z "$DATABASE_URL" ]; then
    echo "Error: DATABASE_URL is required"
    show_usage
fi

# Function to check database connection
check_db_connection() {
    echo "Checking database connection..."
    if ! psql "$DATABASE_URL" -c '\q' 2>/dev/null; then
        echo "Error: Could not connect to database"
        echo "Please check your database connection settings and ensure the database is running"
        exit 1
    fi
    echo "Database connection successful"
}

# Function to run migrations
run_migrations() {
    echo "Running database migrations..."
    
    # Check if alembic directory exists
    if [ ! -d "alembic" ]; then
        echo "Error: alembic directory not found"
        echo "Please ensure you are in the correct directory and alembic is initialized"
        exit 1
    fi

    # Export DATABASE_URL for alembic
    export DATABASE_URL

    # Run migrations
    alembic upgrade head

    if [ $? -eq 0 ]; then
        echo "Migrations completed successfully"
    else
        echo "Error: Migration failed"
        exit 1
    fi
}

# Main execution
echo "Starting database migration process..."

# Check database connection
check_db_connection

# Run migrations
run_migrations

echo "Migration process completed successfully" 