#!/usr/bin/env pwsh
<#
.SYNOPSIS
    Script pour créer les secrets Kubernetes en production

.DESCRIPTION
    Ce script crée les secrets Kubernetes nécessaires pour Lions User Manager :
    - Secret frontend (Keycloak client secret, OIDC encryption secret)
    - Secret backend (Keycloak service account secret, DB password, etc.)

.PARAMETER VpsHost
    Host SSH du VPS (ex: lions@176.57.150.2)

.PARAMETER Namespace
    Namespace Kubernetes (défaut: lions-user-manager)

.PARAMETER FrontendClientSecret
    Secret du client frontend Keycloak

.PARAMETER BackendClientSecret
    Secret du service account backend Keycloak

.PARAMETER OidcEncryptionSecret
    Secret de chiffrement OIDC (32+ caractères)

.PARAMETER KeycloakAdminPassword
    Mot de passe admin Keycloak

.PARAMETER DatabasePassword
    Mot de passe base de données

.PARAMETER BackendUrl
    URL du backend (défaut: https://api.lions.dev/lions-user-manager)

.EXAMPLE
    .\create-kubernetes-secrets-production.ps1 `
        -VpsHost "lions@176.57.150.2" `
        -FrontendClientSecret "frontend-secret" `
        -BackendClientSecret "backend-secret" `
        -OidcEncryptionSecret "32-char-encryption-secret-here" `
        -KeycloakAdminPassword "admin-password" `
        -DatabasePassword "db-password"
#>

param(
    [Parameter(Mandatory=$true)]
    [string]$VpsHost,
    
    [Parameter(Mandatory=$false)]
    [string]$Namespace = "lions-user-manager",
    
    [Parameter(Mandatory=$true)]
    [string]$FrontendClientSecret,
    
    [Parameter(Mandatory=$true)]
    [string]$BackendClientSecret,
    
    [Parameter(Mandatory=$true)]
    [string]$OidcEncryptionSecret,
    
    [Parameter(Mandatory=$true)]
    [string]$KeycloakAdminPassword,
    
    [Parameter(Mandatory=$true)]
    [string]$DatabasePassword,
    
    [Parameter(Mandatory=$false)]
    [string]$BackendUrl = "https://api.lions.dev/lions-user-manager"
)

$ErrorActionPreference = "Stop"

# Couleurs
function Write-Success { Write-Host "✅ $args" -ForegroundColor Green }
function Write-Info { Write-Host "ℹ️  $args" -ForegroundColor Cyan }
function Write-Warning { Write-Host "⚠️  $args" -ForegroundColor Yellow }
function Write-Error { Write-Host "❌ $args" -ForegroundColor Red }
function Write-Step { Write-Host "`n🚀 $args" -ForegroundColor Magenta }

Write-Host @"

╔═══════════════════════════════════════════════════════════════════════════════╗
║                                                                               ║
║        🔐 CRÉATION SECRETS KUBERNETES PRODUCTION 🔐                          ║
║                                                                               ║
╚═══════════════════════════════════════════════════════════════════════════════╝

"@ -ForegroundColor Cyan

Write-Info "VPS Host: $VpsHost"
Write-Info "Namespace: $Namespace"
Write-Info ""

# Vérifier que le namespace existe
Write-Step "1. Vérification du namespace..."

$checkNsCmd = "kubectl get namespace $Namespace"
try {
    ssh.exe $VpsHost $checkNsCmd | Out-Null
    Write-Success "Namespace $Namespace existe"
} catch {
    Write-Info "Création du namespace $Namespace..."
    $createNsCmd = "kubectl create namespace $Namespace"
    ssh.exe $VpsHost $createNsCmd
    Write-Success "Namespace $Namespace créé"
}

# 2. Créer le secret frontend
Write-Step "2. Création du secret frontend..."

$frontendSecretYaml = @"
apiVersion: v1
kind: Secret
metadata:
  name: lions-user-manager-client-secrets
  namespace: $Namespace
type: Opaque
stringData:
  KEYCLOAK_CLIENT_SECRET: $FrontendClientSecret
  OIDC_ENCRYPTION_SECRET: $OidcEncryptionSecret
  LIONS_USER_MANAGER_BACKEND_URL: $BackendUrl
"@

$frontendSecretFile = [System.IO.Path]::GetTempFileName()
$frontendSecretYaml | Out-File -FilePath $frontendSecretFile -Encoding UTF8

try {
    # Supprimer le secret s'il existe déjà
    $deleteCmd = "kubectl delete secret lions-user-manager-client-secrets -n $Namespace --ignore-not-found=true"
    ssh.exe $VpsHost $deleteCmd | Out-Null
    
    # Copier le fichier sur le VPS et créer le secret
    $remoteFile = "/tmp/frontend-secret.yaml"
    scp.exe $frontendSecretFile "$VpsHost`:$remoteFile"
    $createSecretCmd = "kubectl apply -f $remoteFile"
    ssh.exe $VpsHost $createSecretCmd
    
    Write-Success "Secret frontend créé"
} catch {
    Write-Error "Erreur création secret frontend: $($_.Exception.Message)"
    exit 1
} finally {
    Remove-Item $frontendSecretFile -Force
}

# 3. Créer le secret backend
Write-Step "3. Création du secret backend..."

$backendSecretYaml = @"
apiVersion: v1
kind: Secret
metadata:
  name: lions-user-manager-server-secrets
  namespace: $Namespace
type: Opaque
stringData:
  KEYCLOAK_CLIENT_SECRET: $BackendClientSecret
  KEYCLOAK_ADMIN_USERNAME: admin
  KEYCLOAK_ADMIN_PASSWORD: $KeycloakAdminPassword
  DB_PASSWORD: $DatabasePassword
"@

$backendSecretFile = [System.IO.Path]::GetTempFileName()
$backendSecretYaml | Out-File -FilePath $backendSecretFile -Encoding UTF8

try {
    # Supprimer le secret s'il existe déjà
    $deleteCmd = "kubectl delete secret lions-user-manager-server-secrets -n $Namespace --ignore-not-found=true"
    ssh.exe $VpsHost $deleteCmd | Out-Null
    
    # Copier le fichier sur le VPS et créer le secret
    $remoteFile = "/tmp/backend-secret.yaml"
    scp.exe $backendSecretFile "$VpsHost`:$remoteFile"
    $createSecretCmd = "kubectl apply -f $remoteFile"
    ssh.exe $VpsHost $createSecretCmd
    
    Write-Success "Secret backend créé"
} catch {
    Write-Error "Erreur création secret backend: $($_.Exception.Message)"
    exit 1
} finally {
    Remove-Item $backendSecretFile -Force
}

# 4. Vérifier les secrets
Write-Step "4. Vérification des secrets créés..."

$listSecretsCmd = "kubectl get secrets -n $Namespace | grep lions-user-manager"
try {
    $secrets = ssh.exe $VpsHost $listSecretsCmd
    Write-Success "Secrets listés:"
    Write-Host $secrets
} catch {
    Write-Warning "Erreur lors de la vérification: $($_.Exception.Message)"
}

# 5. Décrire les secrets (sans afficher les valeurs)
Write-Step "5. Description des secrets (sans valeurs)..."

try {
    Write-Info "Secret frontend:"
    $describeFrontendCmd = "kubectl describe secret lions-user-manager-client-secrets -n $Namespace"
    ssh.exe $VpsHost $describeFrontendCmd
    
    Write-Info "Secret backend:"
    $describeBackendCmd = "kubectl describe secret lions-user-manager-server-secrets -n $Namespace"
    ssh.exe $VpsHost $describeBackendCmd
} catch {
    Write-Warning "Erreur lors de la description: $($_.Exception.Message)"
}

# 6. Résumé
Write-Step "6. Résumé de la configuration..."

Write-Host @"

╔═══════════════════════════════════════════════════════════════════════════════╗
║                                                                               ║
║                    ✅ SECRETS KUBERNETES CRÉÉS ✅                            ║
║                                                                               ║
╚═══════════════════════════════════════════════════════════════════════════════╝

"@ -ForegroundColor Green

Write-Host "📋 SECRETS CRÉÉS:" -ForegroundColor Yellow
Write-Host ""
Write-Host "🔐 FRONTEND (lions-user-manager-client-secrets):" -ForegroundColor Cyan
Write-Host "   - KEYCLOAK_CLIENT_SECRET"
Write-Host "   - OIDC_ENCRYPTION_SECRET"
Write-Host "   - LIONS_USER_MANAGER_BACKEND_URL"
Write-Host ""
Write-Host "🔐 BACKEND (lions-user-manager-server-secrets):" -ForegroundColor Cyan
Write-Host "   - KEYCLOAK_CLIENT_SECRET"
Write-Host "   - KEYCLOAK_ADMIN_USERNAME"
Write-Host "   - KEYCLOAK_ADMIN_PASSWORD"
Write-Host "   - DB_PASSWORD"
Write-Host ""
Write-Host "⚠️  PROCHAINES ÉTAPES:" -ForegroundColor Yellow
Write-Host "   1. Vérifiez que les secrets sont correctement créés"
Write-Host "   2. Configurez les Deployments pour utiliser ces secrets"
Write-Host "   3. Procédez au déploiement avec lionsctl"
Write-Host ""

