#!/bin/bash

# Help function
usage() {
    echo "Usage: $0 -d <database_url> [-t <target_revision>]"
    echo "  -d : Database URL"
    echo "  -t : Target revision to downgrade to (optional, defaults to -1)"
    exit 1
}

# Parse command line arguments
while getopts "d:t:" opt; do
    case $opt in
        d) DATABASE_URL="$OPTARG" ;;
        t) TARGET_REVISION="$OPTARG" ;;
        ?) usage ;;
    esac
done

# Check if database URL is provided
if [ -z "$DATABASE_URL" ]; then
    echo "Error: Database URL is required"
    usage
fi

# Set default target revision if not provided
if [ -z "$TARGET_REVISION" ]; then
    TARGET_REVISION="-1"
fi

# Export the database URL
export DATABASE_URL

# Run the downgrade
echo "Running alembic downgrade to ${TARGET_REVISION}..."
poetry run alembic downgrade ${TARGET_REVISION} 