<#
.SYNOPSIS
  Prove SQL + Node license capacity enforcement on a throwaway database.
.DESCRIPTION
  Creates a fresh repo via migrate.js, caps InstancesAllowed at 2, seeds ctl.Servers,
  asserts ctl.usp_CheckInstanceCapacity blocks at limit, then asserts
  licenseEngine.assertCanRegisterInstance refuses over-limit in Node.
  Drops the throwaway DB when finished.
#>
[CmdletBinding()]
param(
    [string]$Root = 'K:\RHOYLLE BUSINESS EMPIRE LLC\Business Plans\PRODUCTS\DBAOps-Sovereign',
    [string]$SqlServer = '.'
)

$ErrorActionPreference = 'Stop'
if (-not (Get-Command Invoke-Sqlcmd -ErrorAction SilentlyContinue)) {
    throw 'SqlServer module missing. Install-Module SqlServer -Scope CurrentUser'
}
if (-not (Get-Command node -ErrorAction SilentlyContinue)) { throw 'node not found on PATH' }

$apiDir = Join-Path $Root 'src\api'
$migRel = 'scripts/migrate.js'
$migFull = Join-Path $apiDir 'scripts\migrate.js'
if (-not (Test-Path $migFull)) { throw "migrate.js not found at $migFull" }

function Q([string]$q, [string]$db = 'master') {
    Invoke-Sqlcmd -ServerInstance $SqlServer -Database $db -Query $q -TrustServerCertificate -QueryTimeout 120 -ErrorAction Stop
}

$stamp = Get-Date -Format 'yyyyMMdd_HHmmss'
$proofDb = "SovereignLicenseProof_$stamp"
$connMaster = "Server=$SqlServer;Database=master;Integrated Security=SSPI;TrustServerCertificate=True;"
$connProof = "Server=$SqlServer;Database=$proofDb;Integrated Security=SSPI;TrustServerCertificate=True;"
$connBak = $env:SOVEREIGN_DB_CONNECTION
$passed = $false

Write-Host '=============================================================' -ForegroundColor Cyan
Write-Host 'License Enforcement Proof' -ForegroundColor Cyan
Write-Host "  throwaway : $proofDb"
Write-Host '  cap       : InstancesAllowed = 2'
Write-Host '=============================================================' -ForegroundColor Cyan

try {
    Q "CREATE DATABASE [$proofDb];" 'master' | Out-Null
    $env:SOVEREIGN_DB_CONNECTION = $connMaster
    Push-Location $apiDir
    $null = & node $migRel --database $proofDb 2>&1 | Out-String
    Pop-Location

    Q "UPDATE ctl.LicenseEntitlements SET InstancesAllowed = 2 WHERE IsActive = 1;" $proofDb | Out-Null
    Q 'UPDATE ctl.Servers SET IsActive = 0;' $proofDb | Out-Null

    function Get-Capacity {
        Q 'EXEC ctl.usp_CheckInstanceCapacity;' $proofDb | Select-Object -First 1
    }

    $c0 = Get-Capacity
    if ($c0.CanRegister -ne 1) { throw "Expected CanRegister=1 at 0 servers; got $($c0.CanRegister)" }
    Write-Host '  OK at 0 servers: CanRegister=1' -ForegroundColor Green

    Q "INSERT INTO ctl.Servers (ServerId, ServerName, Engine, IsActive) VALUES (NEWID(), N'proof-seed-1', N'SQL Server', 1);" $proofDb | Out-Null
    $c1 = Get-Capacity
    if ($c1.CanRegister -ne 1) { throw "Expected CanRegister=1 at 1/2 servers; got $($c1.CanRegister)" }
    Write-Host '  OK at 1/2 servers: CanRegister=1' -ForegroundColor Green

    Q "INSERT INTO ctl.Servers (ServerId, ServerName, Engine, IsActive) VALUES (NEWID(), N'proof-seed-2', N'SQL Server', 1);" $proofDb | Out-Null
    $c2 = Get-Capacity
    if ($c2.CanRegister -ne 0) { throw "Expected CanRegister=0 at limit (2/2); got $($c2.CanRegister)" }
    Write-Host '  OK at limit (2/2): CanRegister=0 (refused)' -ForegroundColor Green

    Q "INSERT INTO ctl.Servers (ServerId, ServerName, Engine, IsActive) VALUES (NEWID(), N'proof-over-3', N'SQL Server', 1);" $proofDb | Out-Null
    $c3 = Get-Capacity
    if ($c3.InstancesUsed -lt 3 -or $c3.CanRegister -ne 0) {
        throw "Expected used>=3 and CanRegister=0 over limit; got used=$($c3.InstancesUsed) CanRegister=$($c3.CanRegister)"
    }
    Write-Host '  OK over limit (3/2): CanRegister=0' -ForegroundColor Green

    $nodeScript = Join-Path $Root 'scripts\prove-license-node.js'
    if (-not (Test-Path $nodeScript)) { throw "Missing $nodeScript" }
    $env:SOVEREIGN_DB_CONNECTION = $connProof
    $env:SOVEREIGN_LICENSE_PATH = '__proof_no_manifest__'
    Push-Location $Root
    $nodeOut = & node $nodeScript 2>&1 | Out-String
    $nodeExit = $LASTEXITCODE
    Pop-Location
    Write-Host "  Node assertCanRegisterInstance: $nodeOut"
    if ($nodeExit -ne 0) { throw 'Node layer did not refuse over-limit registration' }
    Write-Host '  OK Node layer: INSTANCE_LIMIT refusal' -ForegroundColor Green

    $passed = $true
    Write-Host ''
    Write-Host 'PROVEN - license enforcement refuses at SQL and Node layers.' -ForegroundColor Green
}
catch {
    Write-Host "FAIL: $($_.Exception.Message)" -ForegroundColor Red
}
finally {
    $env:SOVEREIGN_DB_CONNECTION = $connBak
    Remove-Item Env:SOVEREIGN_LICENSE_PATH -ErrorAction SilentlyContinue
    try {
        Q "IF DB_ID('$proofDb') IS NOT NULL BEGIN ALTER DATABASE [$proofDb] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [$proofDb]; END" 'master' | Out-Null
        Write-Host '  Throwaway DB dropped.' -ForegroundColor Green
    }
    catch {
        Write-Host "  WARNING: drop [$proofDb] manually." -ForegroundColor Red
    }
}

if (-not $passed) { exit 1 }
