param(
    [string]$Host = "120.53.222.17",
    [int]$Port = 5432,
    [string]$AdminUser = "postgres",
    [string]$AdminPassword = ""
)

if (-not (Get-Command psql -ErrorAction SilentlyContinue)) {
    throw "psql command not found. Add PostgreSQL bin directory to PATH."
}

if ([string]::IsNullOrWhiteSpace($AdminPassword)) {
    Write-Warning "AdminPassword not provided. You will be prompted by psql."
}

$sqlPath = Join-Path $PSScriptRoot "create_databases.sql"
if (-not (Test-Path $sqlPath)) {
    throw "Cannot find create_databases.sql under $PSScriptRoot."
}

$env:PGPASSWORD = $AdminPassword

$arguments = @(
    "-h", $Host,
    "-p", $Port,
    "-U", $AdminUser,
    "-f", $sqlPath
)

Write-Host "Executing create_databases.sql on $Host:$Port as $AdminUser ..."
& psql @arguments

if ($LASTEXITCODE -ne 0) {
    throw "psql returned non-zero exit code ($LASTEXITCODE)."
}

Write-Host "PostgreSQL databases and roles ensured successfully."
