#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

usage() {
    echo "Usage: $0 {start|stop|reset|status}"
    echo ""
    echo "Commands:"
    echo "  start   Start the development PostgreSQL database"
    echo "  stop    Stop the development database"
    echo "  reset   Stop, destroy volume, and restart fresh"
    echo "  status  Show container status"
    exit 1
}

if [[ $# -lt 1 ]]; then
    usage
fi

if ! command -v docker &>/dev/null; then
    echo "Error: docker is not installed or not on PATH."
    echo "Install Docker Desktop: https://www.docker.com/products/docker-desktop/"
    exit 1
fi

if ! docker info &>/dev/null; then
    echo "Error: Docker daemon is not running. Start Docker Desktop first."
    exit 1
fi

case "$1" in
    start)
        echo "Starting qc-trace dev database..."
        docker compose -f "$PROJECT_ROOT/docker-compose.yml" up -d
        echo "Waiting for postgres to be ready..."
        docker compose -f "$PROJECT_ROOT/docker-compose.yml" exec -T postgres \
            pg_isready -U qc_trace -d qc_trace --timeout=30
        echo "Database ready at localhost:5432"
        ;;
    stop)
        echo "Stopping qc-trace dev database..."
        docker compose -f "$PROJECT_ROOT/docker-compose.yml" down
        echo "Stopped."
        ;;
    reset)
        echo "Resetting qc-trace dev database (destroying data)..."
        docker compose -f "$PROJECT_ROOT/docker-compose.yml" down -v
        docker compose -f "$PROJECT_ROOT/docker-compose.yml" up -d
        echo "Waiting for postgres to be ready..."
        docker compose -f "$PROJECT_ROOT/docker-compose.yml" exec -T postgres \
            pg_isready -U qc_trace -d qc_trace --timeout=30
        echo "Database reset and ready at localhost:5432"
        ;;
    status)
        docker compose -f "$PROJECT_ROOT/docker-compose.yml" ps
        ;;
    *)
        usage
        ;;
esac
