<#
.SYNOPSIS
  Grant lifetime Unlimited license for all DBAOps Sovereign products (RHOYLLE founder).
.EXAMPLE
  .\scripts\grant-lifetime-license.ps1
  .\scripts\grant-lifetime-license.ps1 -SqlServer . -Database SovereignRepository
#>
[CmdletBinding()]
param(
    [string]$SqlServer = $env:COMPUTERNAME,
    [string]$Database = 'SovereignRepository'
)

$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path $PSScriptRoot -Parent
$sqlFile = Join-Path $repoRoot 'src\database\schema-v22-lifetime-license-rhoylle.sql'

if (-not (Test-Path $sqlFile)) {
    throw "Missing $sqlFile"
}

Write-Host '=== DBAOps Sovereign - Lifetime license (Unlimited / perpetual) ===' -ForegroundColor Cyan
Write-Host "Server: $SqlServer  Database: $Database"

sqlcmd -S $SqlServer -E -d $Database -i $sqlFile
if ($LASTEXITCODE -ne 0) { throw 'License SQL failed' }

Write-Host ''
Write-Host 'Signing offline license manifest...' -ForegroundColor Cyan
node (Join-Path $repoRoot 'scripts\sign-license-manifest.js') --template (Join-Path $repoRoot 'license\manifest-rhoylle-unlimited.json') --out (Join-Path $repoRoot 'license\rhoylle.lifetime.license')
if ($LASTEXITCODE -ne 0) { Write-Warning 'License signing skipped — run generate-license-keys.js first' }

Write-Host ''
Write-Host 'Verifying license row...' -ForegroundColor Cyan
sqlcmd -S $SqlServer -E -d $Database -Q "SET NOCOUNT ON; SELECT Edition, Tier, InstancesAllowed, ExpiresAt, IsActive, LicenseKey FROM ctl.LicenseEntitlements WHERE IsActive = 1" -W -s "|"

$api = 'http://localhost:3041'
try {
    $lic = Invoke-RestMethod -Uri "$api/api/license/public" -TimeoutSec 8
    Write-Host ''
    Write-Host 'API license snapshot:' -ForegroundColor Green
    Write-Host "  Edition:   $($lic.edition)"
    Write-Host "  Tier:      $($lic.tier)"
    Write-Host "  Status:    $($lic.status)"
    Write-Host "  Instances: $($lic.instancesUsed)/$($lic.instancesAllowed)"
    Write-Host "  Expires:   $(if ($lic.expiresAt) { $lic.expiresAt } else { 'Never (lifetime)' })"
} catch {
    Write-Warning "API not reachable at $api - restart npm start to pick up license in UI."
}

Write-Host ''
Write-Host 'Done. All suites and feature gates are open under Unlimited tier.' -ForegroundColor Green
