<#

.SYNOPSIS

  Remove SovereignRepository and optional local artifacts (customer teardown).

#>

[CmdletBinding(SupportsShouldProcess)]

param(

    [string]$SqlServer = '.',

    [string]$Database = 'SovereignRepository',

    [switch]$DropDatabase,

    [switch]$RemoveLocalReleases,

    [switch]$DropCollectorLogin,

    [string]$CollectorLogin = 'dbaops_collector'

)



$ErrorActionPreference = 'Stop'

$repoRoot = Split-Path $PSScriptRoot -Parent



Write-Host '=== DBAOps Sovereign uninstall ===' -ForegroundColor Cyan



if ($DropCollectorLogin -and $PSCmdlet.ShouldProcess($CollectorLogin, 'Drop collector login on instance')) {

    sqlcmd -S $SqlServer -E -d master -Q @"

IF EXISTS (SELECT 1 FROM sys.server_principals WHERE name = N'$CollectorLogin')

  DROP LOGIN [$CollectorLogin];

"@ -b 2>$null

    Write-Host "Removed login $CollectorLogin (if present)." -ForegroundColor Green

}



if ($PSCmdlet.ShouldProcess("$SqlServer/$Database", 'Drop Sovereign repository database')) {

    if ($DropDatabase) {

        sqlcmd -S $SqlServer -E -d master -Q @"

IF DB_ID(N'$Database') IS NOT NULL

BEGIN

  ALTER DATABASE [$Database] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

  DROP DATABASE [$Database];

END

"@ -b

        Write-Host "Dropped database $Database" -ForegroundColor Green

    } else {

        Write-Host 'Skipped database drop (pass -DropDatabase to remove SovereignRepository).' -ForegroundColor Yellow

    }

}



if ($RemoveLocalReleases -and $PSCmdlet.ShouldProcess($repoRoot, 'Remove local release artifacts')) {

    foreach ($sub in @('_staging', '_uploads', 'sovereign-platform', 'sovereign-collector')) {

        $p = Join-Path $repoRoot "releases\$sub"

        if (Test-Path $p) { Remove-Item $p -Recurse -Force }

    }

    Write-Host 'Local release build artifacts removed.' -ForegroundColor Green

}



Write-Host 'Stop services: npm run stop:sovereign' -ForegroundColor Gray

Write-Host 'See docs/UNINSTALL.md for target-side grant reversal.' -ForegroundColor Gray

Write-Host 'Uninstall complete.' -ForegroundColor Green

