# ═══════════════════════════════════════════════════════════════════════════
# MailFlow - Appwrite CORS Platform Setup (Vollautomatisch via API)
# ═══════════════════════════════════════════════════════════════════════════
# Dieses Script versucht, die Platform automatisch über die Appwrite API
# hinzuzufügen. Falls der API Key nicht die richtigen Scopes hat, wird
# eine Anleitung zur manuellen Einrichtung angezeigt.
# ═══════════════════════════════════════════════════════════════════════════

param(
    [string]$AppwriteUrl = "https://appwrite.webklar.com",
    [string]$ProjectId = "",
    [string]$ApiKey = "",
    [string]$PlatformHostname = "emailsorter.webklar.com",
    [string]$PlatformOrigin = "https://emailsorter.webklar.com"
)

# Lade .env Datei falls vorhanden
$envFile = "..\server\.env"
if (Test-Path $envFile) {
    Get-Content $envFile | ForEach-Object {
        if ($_ -match '^\s*([^#][^=]*)=(.*)$') {
            $key = $matches[1].Trim()
            $value = $matches[2].Trim()
            [Environment]::SetEnvironmentVariable($key, $value, "Process")
        }
    }
}

# Verwende Werte aus .env falls nicht als Parameter übergeben
if ([string]::IsNullOrEmpty($ProjectId)) {
    $ProjectId = $env:APPWRITE_PROJECT_ID
}
if ([string]::IsNullOrEmpty($ApiKey)) {
    $ApiKey = $env:APPWRITE_API_KEY
}
if ([string]::IsNullOrEmpty($AppwriteUrl) -or $AppwriteUrl -eq "https://appwrite.webklar.com") {
    $endpoint = $env:APPWRITE_ENDPOINT
    if ($endpoint) {
        $AppwriteUrl = $endpoint -replace '/v1$', ''
    }
}

if ([string]::IsNullOrEmpty($ProjectId) -or [string]::IsNullOrEmpty($ApiKey)) {
    Write-Host "❌ Fehlende Konfiguration!" -ForegroundColor Red
    Write-Host "   Bitte setze APPWRITE_PROJECT_ID und APPWRITE_API_KEY in server/.env" -ForegroundColor Yellow
    Write-Host "   Oder gib sie als Parameter an: -ProjectId <id> -ApiKey <key>" -ForegroundColor Yellow
    exit 1
}

Write-Host "`n🔧 Appwrite CORS Platform Setup (API)" -ForegroundColor Cyan
Write-Host "═══════════════════════════════════════════════════════════════" -ForegroundColor Cyan
Write-Host ""
Write-Host "Appwrite URL:     $AppwriteUrl" -ForegroundColor Gray
Write-Host "Project ID:       $ProjectId" -ForegroundColor Gray
Write-Host "Platform Host:    $PlatformHostname" -ForegroundColor Gray
Write-Host "Platform Origin:  $PlatformOrigin" -ForegroundColor Gray
Write-Host ""

# Versuche Platform über API hinzuzufügen
Write-Host "📡 Versuche Platform über API hinzuzufügen..." -ForegroundColor Yellow

$headers = @{
    "X-Appwrite-Project" = $ProjectId
    "X-Appwrite-Key" = $ApiKey
    "Content-Type" = "application/json"
}

$body = @{
    type = "web"
    name = "Production"
    hostname = $PlatformHostname
} | ConvertTo-Json

try {
    $response = Invoke-RestMethod -Uri "$AppwriteUrl/v1/projects/$ProjectId/platforms" `
        -Method POST `
        -Headers $headers `
        -Body $body `
        -ErrorAction Stop
    
    Write-Host ""
    Write-Host "✅ Platform erfolgreich hinzugefügt!" -ForegroundColor Green
    Write-Host "   Name: $($response.name)" -ForegroundColor Gray
    Write-Host "   Hostname: $($response.hostname)" -ForegroundColor Gray
    Write-Host ""
    Write-Host "📝 Warte 1-2 Minuten, damit die CORS-Änderungen wirksam werden." -ForegroundColor Yellow
    Write-Host "   Danach sollten die CORS-Fehler verschwinden." -ForegroundColor Yellow
    Write-Host ""
    
} catch {
    $statusCode = $_.Exception.Response.StatusCode.value__
    $errorMessage = $_.Exception.Message
    
    Write-Host ""
    Write-Host "❌ API-Aufruf fehlgeschlagen: HTTP $statusCode" -ForegroundColor Red
    
    if ($statusCode -eq 401) {
        Write-Host ""
        Write-Host "⚠️  Der API Key hat nicht die erforderlichen Berechtigungen!" -ForegroundColor Yellow
        Write-Host ""
        Write-Host "💡 Lösung:" -ForegroundColor Cyan
        Write-Host "   1. Gehe zu $AppwriteUrl" -ForegroundColor White
        Write-Host "   2. Öffne dein Projekt" -ForegroundColor White
        Write-Host "   3. Gehe zu Settings → API Credentials" -ForegroundColor White
        Write-Host "   4. Erstelle einen neuen API Key mit folgenden Scopes:" -ForegroundColor White
        Write-Host "      - platforms.read" -ForegroundColor Gray
        Write-Host "      - platforms.write" -ForegroundColor Gray
        Write-Host "   5. Aktualisiere APPWRITE_API_KEY in server/.env" -ForegroundColor White
        Write-Host "   6. Führe dieses Script erneut aus" -ForegroundColor White
        Write-Host ""
    }
    
    Write-Host "💡 Alternative: Verwende die manuelle Methode:" -ForegroundColor Cyan
    Write-Host "   1. Gehe zu $AppwriteUrl" -ForegroundColor White
    Write-Host "   2. Öffne dein Projekt" -ForegroundColor White
    Write-Host "   3. Gehe zu Settings → Platforms" -ForegroundColor White
    Write-Host "   4. Klicke auf 'Add Platform' → 'Web'" -ForegroundColor White
    Write-Host "   5. Fülle aus:" -ForegroundColor White
    Write-Host "      - Name: Production" -ForegroundColor Gray
    Write-Host "      - Hostname: $PlatformHostname" -ForegroundColor Gray
    Write-Host "      - Origin: $PlatformOrigin" -ForegroundColor Gray
    Write-Host "   6. Speichere und warte 1-2 Minuten" -ForegroundColor White
    Write-Host ""
    
    exit 1
}
