$ErrorActionPreference = "Stop"
$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $projectRoot

$binDir = "C:\Program Files\MariaDB 12.1\bin"
$installExe = Join-Path $binDir "mariadb-install-db.exe"
$serverExe = Join-Path $binDir "mariadbd.exe"
$dataDir = "C:\Users\stari\mariadb-data"
$dbPassword = "changeme"

if (-not (Test-Path $serverExe)) {
  Write-Error "MariaDB server not found at $serverExe. Install MariaDB first."
}

$mysqlRunning = Get-Process -Name mariadbd -ErrorAction SilentlyContinue
if (-not $mysqlRunning) {
  if (-not (Test-Path $dataDir)) {
    New-Item -ItemType Directory -Path $dataDir | Out-Null
    & $installExe -d $dataDir -p $dbPassword | Out-Host
  }

  $defaultsFile = Join-Path $dataDir "my.ini"
  Start-Process -FilePath $serverExe -ArgumentList "--defaults-file=$defaultsFile", "--console" -WindowStyle Hidden
  Start-Sleep -Seconds 3
}

if (-not (Test-Path (Join-Path $projectRoot "node_modules"))) {
  npm install | Out-Host
}

# Do not auto-seed on startup. Run `npm run seed` manually only when you want sample data.
npm start
