$ErrorActionPreference = "Stop"

$CONTAINER = "hotel-mysql"
$IMAGE     = "mysql:8.4"
$ROOT_PASSWORD = "hotel2025root"
$DATABASE  = "hotel_reservations"
$PORT      = "13306"

$SQL_DIR = Resolve-Path "$PSScriptRoot\..\sql"

$exists = docker ps -a --format '{{.Names}}' | Where-Object { $_ -eq $CONTAINER }

if ($exists) {
    Write-Host "Container '$CONTAINER' already exists -- starting it."
    docker start $CONTAINER
} else {
    Write-Host "Creating and starting '$CONTAINER'."
    docker run -d `
        --name $CONTAINER `
        -e MYSQL_ROOT_PASSWORD=$ROOT_PASSWORD `
        -e MYSQL_DATABASE=$DATABASE `
        -p "${PORT}:3306" `
        -v "${CONTAINER}-data:/var/lib/mysql" `
        -v "${SQL_DIR}\schema.sql:/docker-entrypoint-initdb.d/01_schema.sql:ro" `
        $IMAGE
}

Write-Host "Waiting for MySQL to be ready..."
while ($true) {
    $result = docker exec $CONTAINER mysqladmin ping -uroot -p"$ROOT_PASSWORD" --silent 2>$null
    if ($LASTEXITCODE -eq 0) { break }
    Start-Sleep -Seconds 1
}

Write-Host "MySQL 8.4 is up."
Write-Host "  Host:     127.0.0.1:${PORT}"
Write-Host "  Database: $DATABASE"
Write-Host "  User:     root / $ROOT_PASSWORD"
