# Create Test API Key using EF Core DbContext
# This script uses dotnet ef dbcontext to execute SQL

param(
    [string]$ConnectionString = "Host=localhost;Port=5432;Database=colaflow_identity;Username=colaflow;Password=colaflow_dev_password"
)

Write-Host "Creating test API key..." -ForegroundColor Cyan

# Test API Key
$PlainKey = "cola_test_runtime_validation_2025"
Write-Host "Plain Key (SAVE THIS): $PlainKey" -ForegroundColor Yellow

# Compute SHA-256 hash
$KeyBytes = [System.Text.Encoding]::UTF8.GetBytes($PlainKey)
$HashAlgorithm = [System.Security.Cryptography.SHA256]::Create()
$HashBytes = $HashAlgorithm.ComputeHash($KeyBytes)
$KeyHash = [System.BitConverter]::ToString($HashBytes).Replace("-", "").ToLower()

$KeyPrefix = $PlainKey.Substring(0, 12) + "..."

$TestTenantId = "00000000-0000-0000-0000-000000000001"
$TestUserId = "00000000-0000-0000-0000-000000000001"
$TestApiKeyId = [Guid]::NewGuid().ToString()
$ExpiresAt = (Get-Date).AddDays(30).ToString("yyyy-MM-dd HH:mm:ss")
$CreatedAt = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")

$Sql = @"
INSERT INTO mcp.api_keys (
    id,
    name,
    description,
    key_hash,
    key_prefix,
    tenant_id,
    created_by,
    "read",
    write,
    allowed_resources,
    allowed_tools,
    ip_whitelist,
    expires_at,
    created_at,
    last_used_at,
    revoked_at,
    revoked_by
) VALUES (
    '$TestApiKeyId',
    'SDK Runtime Test Key',
    'Auto-generated test key for MCP SDK runtime validation',
    '$KeyHash',
    '$KeyPrefix',
    '$TestTenantId',
    '$TestUserId',
    true,
    true,
    '{}',
    '{}',
    '{}',
    '$ExpiresAt',
    '$CreatedAt',
    NULL,
    NULL,
    NULL
)
ON CONFLICT (id) DO NOTHING;
"@

# Write SQL to temp file
$TempSqlFile = [System.IO.Path]::GetTempFileName() + ".sql"
$Sql | Out-File -FilePath $TempSqlFile -Encoding UTF8

Write-Host "SQL file created: $TempSqlFile" -ForegroundColor Gray

# Try to find PostgreSQL client
$PsqlPaths = @(
    "C:\Program Files\PostgreSQL\16\bin\psql.exe",
    "C:\Program Files\PostgreSQL\15\bin\psql.exe",
    "C:\Program Files\PostgreSQL\14\bin\psql.exe",
    "C:\PostgreSQL\bin\psql.exe"
)

$Psql = $null
foreach ($Path in $PsqlPaths) {
    if (Test-Path $Path) {
        $Psql = $Path
        break
    }
}

if ($Psql) {
    Write-Host "Found psql at: $Psql" -ForegroundColor Green

    # Execute SQL
    $env:PGPASSWORD = "colaflow_dev_password"
    & $Psql -h localhost -U colaflow -d colaflow_identity -f $TempSqlFile

    Write-Host ""
    Write-Host "Test API Key created successfully!" -ForegroundColor Green
    Write-Host "API Key ID: $TestApiKeyId" -ForegroundColor Yellow
    Write-Host "Plain Key: $PlainKey" -ForegroundColor Yellow
    Write-Host "Key Hash: $KeyHash" -ForegroundColor Gray
    Write-Host "Expires At: $ExpiresAt" -ForegroundColor Gray
}
else {
    Write-Host "PostgreSQL client (psql) not found." -ForegroundColor Red
    Write-Host "Please install PostgreSQL client or manually execute the SQL:" -ForegroundColor Yellow
    Write-Host ""
    Write-Host $Sql -ForegroundColor Gray
    Write-Host ""
    Write-Host "After executing the SQL, use this API key:" -ForegroundColor Yellow
    Write-Host "  Authorization: Bearer $PlainKey" -ForegroundColor Cyan
}

# Clean up temp file
Remove-Item -Path $TempSqlFile -ErrorAction SilentlyContinue
