<#
.SYNOPSIS
  Data-driven collection — resolves ctl.Servers via catalog, then runs the fleet collector.
.EXAMPLE
  .\scripts\Invoke-SovereignCollection.ps1 -SubmitAll
  .\scripts\Invoke-SovereignCollection.ps1 -SubmitAll -FallbackDiscover
  .\scripts\Invoke-SovereignCollection.ps1 -ServerId '00000000-0000-0000-0000-000000000000' -SubmitTelemetry
#>
[CmdletBinding()]
param(
    [string]$SovereignApi = 'http://localhost:3041',
    [string]$RepositoryConnection,
    [ValidateSet('Auto', 'Api', 'Sql')]
    [string]$Source = 'Auto',
    [string]$ServerId,
    [switch]$FallbackDiscover,
    [switch]$SubmitTelemetry,
    [switch]$SubmitFleetFacts,
    [switch]$SubmitWaitStats,
    [switch]$SubmitDatabaseHealth,
    [switch]$SubmitQueryStats,
    [switch]$SubmitTechnologyDetection,
    [switch]$SubmitAgentStatus,
    [switch]$SubmitSecurity,
    [switch]$SubmitAll,
    [switch]$RegisterIfMissing,
    [string]$IngestKey = '',
    [string]$BearerToken = '',
    [System.Management.Automation.PSCredential]$SqlCredential
)

$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path $PSScriptRoot -Parent
. (Join-Path $PSScriptRoot 'lib\Resolve-SovereignConnection.ps1')
. (Join-Path $PSScriptRoot 'lib\Get-SovereignCredential.ps1')

Write-Host '=== DBAOps Sovereign — Catalog-driven collection ===' -ForegroundColor Cyan
try {
    Invoke-RestMethod -Uri "$($SovereignApi.TrimEnd('/'))/api/health" -TimeoutSec 8 | Out-Null
} catch {
    throw "API not running at $SovereignApi — run npm start first."
}

$targets = @()
try {
    $targets = @(Get-SovereignCollectionTargets -SovereignApi $SovereignApi -RepositoryConnection $RepositoryConnection -Source $Source -ServerId $ServerId)
} catch {
    Write-Warning "Catalog resolver failed: $($_.Exception.Message)"
}

if ($targets.Count -eq 0 -and $FallbackDiscover) {
    Write-Host 'Catalog empty — falling back to local SQL instance discovery (not hardcoded hosts).' -ForegroundColor Yellow
    . (Join-Path $PSScriptRoot 'Discover-SqlInstances.ps1')
    $discovered = Get-LocalSqlInstanceConnectNames
    foreach ($d in $discovered) {
        $targets += [pscustomobject]@{
            serverId = $null
            serverName = $d.ConnectName
            connectName = $d.ConnectName
            engine = 'SQL Server'
            authMode = 'Integrated'
            isCollectable = $true
        }
    }
}

if ($targets.Count -eq 0) {
    throw @'
No collection targets. Register SQL instances in ctl.Servers (Fleet Manage / POST /api/fleet/register)
or pass -FallbackDiscover for local instance discovery.
'@
}

Write-Host "Resolved $($targets.Count) target(s) from catalog:" -ForegroundColor Green
foreach ($t in $targets) {
    Write-Host "  [$($t.serverId)] $($t.serverName) -> $($t.connectName) ($($t.authMode))"
}

$integrated = @($targets | Where-Object {
    $_.isCollectable -and (($_.authMode -eq 'Integrated') -or [string]::IsNullOrWhiteSpace($_.authMode))
})
$sqlAuth = @($targets | Where-Object { $_.isCollectable -and $_.authMode -eq 'SqlAuth' })

$collector = Join-Path $repoRoot 'src\collectors\DBAOps-Sovereign-Collector.ps1'
$common = @{
    SovereignApi = $SovereignApi
    SubmitTelemetry = $SubmitTelemetry
    SubmitFleetFacts = $SubmitFleetFacts
    SubmitWaitStats = $SubmitWaitStats
    SubmitDatabaseHealth = $SubmitDatabaseHealth
    SubmitQueryStats = $SubmitQueryStats
    SubmitTechnologyDetection = $SubmitTechnologyDetection
    SubmitAgentStatus = $SubmitAgentStatus
    SubmitSecurity = $SubmitSecurity
    SubmitAll = $SubmitAll
    RegisterIfMissing = $RegisterIfMissing
    IngestKey = $IngestKey
    BearerToken = $BearerToken
}

if ($integrated.Count -gt 0) {
    $names = @($integrated | ForEach-Object { $_.connectName } | Select-Object -Unique)
    & $collector @common -ServerList $names
}

foreach ($t in $sqlAuth) {
    $cred = $SqlCredential
    if (-not $cred -and $t.credentialRef) {
        $cred = Get-SovereignCredentialForRef -RefKey $t.credentialRef -RepositoryConnection $RepositoryConnection
    }
    if (-not $cred) {
        Write-Warning "SqlAuth target $($t.connectName) — set -SqlCredential or env SOVEREIGN_CRED_*_USER/PASSWORD for ref '$($t.credentialRef)'"
        continue
    }
    Write-Host "SQL auth collection: $($t.connectName) (ref=$($t.credentialRef))" -ForegroundColor Cyan
    & $collector @common -ServerList @($t.connectName) -SqlCredential $cred
}

Write-Host ''
Write-Host 'Catalog-driven collection complete.' -ForegroundColor Green
