#!/bin/bash
# db.sh - Manage database containers

set -e

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

usage() {
    echo "Usage: $0 <mysql|mssql> [--clean] [--users] [--down]"
    echo ""
    echo "Options:"
    echo "  mysql|mssql  Which database to start"
    echo "  --clean      Delete volumes and start fresh"
    echo "  --users      Only import test users (database must be running)"
    echo "  --down       Stop the database container"
    exit 1
}

# Parse parameters
DB=""
CLEAN=false
USERS_ONLY=false
DOWN_ONLY=false

for arg in "$@"; do
    case $arg in
        mysql|mssql)
            DB=$arg
            ;;
        --clean)
            CLEAN=true
            ;;
        --users)
            USERS_ONLY=true
            ;;
        --down)
            DOWN_ONLY=true
            ;;
        *)
            usage
            ;;
    esac
done

[ -z "$DB" ] && usage

# Stop container only
if [ "$DOWN_ONLY" = true ]; then
    if [ "$DB" = "mysql" ]; then
        echo "==> Stopping MySQL..."
        podman-compose down 2>/dev/null || true
    elif [ "$DB" = "mssql" ]; then
        echo "==> Stopping MSSQL..."
        podman-compose --profile mssql down 2>/dev/null || true
    fi
    echo "==> Done!"
    exit 0
fi

# Import users only
if [ "$USERS_ONLY" = true ]; then
    if [ "$DB" = "mysql" ]; then
        echo "==> Importing users into MySQL..."
        DB_USER=$(grep SPRING_DATASOURCE_USERNAME .env | cut -d= -f2)
        DB_PASS=$(grep SPRING_DATASOURCE_PASSWORD .env | cut -d= -f2)
        podman exec -i lcc-mysql-local mysql -u"${DB_USER}" -p"${DB_PASS}" lcc \
            < src/test/resources/master_data/users.sql
        echo "==> Users imported!"
    elif [ "$DB" = "mssql" ]; then
        echo "==> Importing users into MSSQL..."
        DB_PASS=$(grep DB_ROOT_PASSWORD .env.mssql | cut -d= -f2)
        podman exec -e "SQLCMDPASSWORD=${DB_PASS}" lcc-mssql-local /opt/mssql-tools18/bin/sqlcmd \
            -S localhost -U sa -d lcc -C \
            -i /dev/stdin < src/test/resources/master_data/users_mssql.sql
        echo "==> Users imported!"
    fi
    exit 0
fi

echo "==> Stopping all DB containers..."
podman-compose --profile mssql down 2>/dev/null || true

if [ "$CLEAN" = true ]; then
    echo "==> Deleting volumes..."
    podman volume rm lcc_tool_mysql-data-local 2>/dev/null || true
    podman volume rm lcc_tool_mssql-data-local 2>/dev/null || true
fi

echo "==> Linking .env -> .env.$DB"
rm -f .env
ln -s .env.$DB .env

# Check if volume exists (for init decision)
VOLUME_EXISTS=false
if [ "$DB" = "mysql" ]; then
    podman volume exists lcc_tool_mysql-data-local 2>/dev/null && VOLUME_EXISTS=true
elif [ "$DB" = "mssql" ]; then
    podman volume exists lcc_tool_mssql-data-local 2>/dev/null && VOLUME_EXISTS=true
fi

echo "==> Starting $DB..."
if [ "$DB" = "mysql" ]; then
    podman-compose up -d mysql

    echo "==> Waiting for MySQL..."
    until podman exec lcc-mysql-local mysqladmin ping -h localhost --silent 2>/dev/null; do
        sleep 2
    done
    echo "==> MySQL is ready!"

elif [ "$DB" = "mssql" ]; then
    podman-compose --profile mssql up -d mssql

    echo "==> Waiting for MSSQL..."
    until [ "$(podman inspect -f '{{.State.Health.Status}}' lcc-mssql-local 2>/dev/null)" = "healthy" ]; do
        sleep 2
    done
    echo "==> MSSQL is ready!"

    if [ "$VOLUME_EXISTS" = false ]; then
        echo "==> New volume detected, creating database..."
        DB_PASS=$(grep DB_ROOT_PASSWORD .env | cut -d= -f2)
        podman exec lcc-mssql-local /opt/mssql-tools18/bin/sqlcmd \
            -S localhost -U sa -P "${DB_PASS}" -C \
            -Q "IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = 'lcc') CREATE DATABASE lcc"
        echo "==> Database 'lcc' created!"
    fi
fi

echo "==> Done! .env points to .env.$DB"