# Resolve ctl.CredentialReference -> PSCredential (never stores secrets in SQL)
. (Join-Path $PSScriptRoot 'SovereignEnv.ps1')

function Get-SovereignCredentialFromEnvPrefix {
    param([Parameter(Mandatory)][string]$EnvPrefix)
    $userVar = "${EnvPrefix}_USER"
    $passVar = "${EnvPrefix}_PASSWORD"
    $user = [Environment]::GetEnvironmentVariable($userVar)
    $pass = [Environment]::GetEnvironmentVariable($passVar)
    if (-not $user) {
        $map = Get-SovereignEnvMap
        if ($map[$userVar]) { $user = $map[$userVar] }
        if ($map[$passVar]) { $pass = $map[$passVar] }
    }
    if (-not $user) { return $null }
    $sec = ConvertTo-SecureString ($pass ?? '') -AsPlainText -Force
    return New-Object System.Management.Automation.PSCredential($user, $sec)
}

function Get-SovereignCredentialFromWindowsTarget {
    param([Parameter(Mandatory)][string]$Target)
    try {
        return Get-StoredCredential -Target $Target -ErrorAction Stop
    } catch {
        try {
            $raw = cmdkey /list:$Target 2>$null
            if (-not $raw) { return $null }
            Write-Warning "Windows credential target '$Target' exists but Get-StoredCredential unavailable — use EnvVar source or install CredentialManager module."
        } catch { }
        return $null
    }
}

function Get-SovereignCredentialForRef {
    param(
        [string]$RefKey,
        [string]$RepositoryConnection
    )
    if ([string]::IsNullOrWhiteSpace($RefKey)) { return $null }
    if ($RefKey -eq 'integrated-default') { return $null }

    $cs = Get-SovereignRepositoryConnectionString -Override $RepositoryConnection
    if (-not $cs) { return $null }

    Add-Type -AssemblyName 'System.Data' -ErrorAction SilentlyContinue
    $conn = New-Object System.Data.SqlClient.SqlConnection $cs
    $conn.Open()
    try {
        $cmd = $conn.CreateCommand()
        $cmd.CommandText = 'SELECT SecretSource, EnvPrefix, WindowsTarget FROM ctl.CredentialReference WHERE RefKey = @k'
        $p = $cmd.Parameters.Add('@k', [System.Data.SqlDbType]::NVarChar, 64)
        $p.Value = $RefKey
        $r = $cmd.ExecuteReader()
        if (-not $r.Read()) { return $null }
        $source = [string]$r['SecretSource']
        $prefix = if ($r['EnvPrefix'] -is [DBNull]) { $null } else { [string]$r['EnvPrefix'] }
        $win = if ($r['WindowsTarget'] -is [DBNull]) { $null } else { [string]$r['WindowsTarget'] }
        $r.Close()

        switch ($source) {
            'Integrated' { return $null }
            'EnvVar' {
                if (-not $prefix) { $prefix = "SOVEREIGN_CRED_$($RefKey.ToUpper())" }
                return Get-SovereignCredentialFromEnvPrefix -EnvPrefix $prefix
            }
            'WindowsCredential' {
                if ($win) { return Get-SovereignCredentialFromWindowsTarget -Target $win }
            }
        }
    } finally {
        $conn.Close()
    }
    return $null
}
