# Rebuild msnodesqlv8 for the current Node.js version (Windows Integrated Auth).
# Usage: npm run repair:sql
$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent $PSScriptRoot
$apiDir = Join-Path $root 'src\api'

$nodeVer = node -p 'process.version'
$major = [int](node -p "process.versions.node.split('.')[0]")
Write-Host '=== DBAOps Sovereign - repair SQL native driver ===' -ForegroundColor Cyan
Write-Host "Node $nodeVer"

if ($major -ge 24) {
  Write-Host ''
  Write-Host "ERROR: Node.js $major is not supported by msnodesqlv8 prebuilds yet." -ForegroundColor Red
  Write-Host 'Install Node 22 LTS, then run this script again:' -ForegroundColor Yellow
  Write-Host '  winget install OpenJS.NodeJS.22'
  Write-Host '  (close PowerShell, open new window — node -v must show v22.x)'
  Write-Host '  npm run repair:sql'
  Write-Host ''
  Write-Host 'Or download Node 22 LTS from https://nodejs.org/ and reopen PowerShell.'
  exit 1
}

Push-Location $apiDir
try {
  Write-Host "Rebuilding msnodesqlv8 in $apiDir ..."
  npm rebuild msnodesqlv8
  Write-Host 'Verifying native module load ...'
  node scripts/verify-msnodesqlv8.js
  Write-Host 'Done. Restart the API with npm start' -ForegroundColor Green
} finally {
  Pop-Location
}
