# Script PowerShell pour configurer Keycloak pour l'application JSF BTPXpress
# Port: 8081 (Quarkus + JSF + PrimeFaces)

Write-Host "Configuration Keycloak pour BTPXpress Client JSF" -ForegroundColor Green
Write-Host "=============================================" -ForegroundColor Cyan

$KEYCLOAK_URL = "https://security.lions.dev"
$REALM = "btpxpress"
$CLIENT_ID = "btpxpress-frontend"
$ADMIN_USER = "admin"
$ADMIN_PASSWORD = "KeycloakAdmin2025!"

# Fonction pour obtenir le token d'administration
function Get-AdminToken {
    Write-Host "Recuperation du token admin..." -ForegroundColor Yellow

    $body = @{
        grant_type = "password"
        client_id = "admin-cli"
        username = $ADMIN_USER
        password = $ADMIN_PASSWORD
    }

    try {
        $response = Invoke-RestMethod -Uri "$KEYCLOAK_URL/realms/master/protocol/openid-connect/token" `
            -Method Post `
            -ContentType "application/x-www-form-urlencoded" `
            -Body $body

        Write-Host "Token admin recupere" -ForegroundColor Green
        return $response.access_token
    }
    catch {
        Write-Host "Erreur lors de la recuperation du token: $_" -ForegroundColor Red
        exit 1
    }
}

# Fonction pour obtenir la configuration du client
function Get-ClientConfig {
    param([string]$Token)

    Write-Host "Recuperation de la configuration du client $CLIENT_ID..." -ForegroundColor Yellow

    $headers = @{
        Authorization = "Bearer $Token"
        Accept = "application/json"
    }

    try {
        $clients = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/clients" `
            -Method Get `
            -Headers $headers

        $client = $clients | Where-Object { $_.clientId -eq $CLIENT_ID }

        if ($client) {
            Write-Host "Client trouve: $($client.clientId)" -ForegroundColor Green
            return $client
        }
        else {
            Write-Host "Client $CLIENT_ID non trouve" -ForegroundColor Red
            exit 1
        }
    }
    catch {
        Write-Host "Erreur lors de la recuperation du client: $_" -ForegroundColor Red
        exit 1
    }
}

# Fonction pour mettre a jour les redirect URIs
function Update-ClientRedirectUris {
    param(
        [string]$Token,
        [object]$Client
    )

    Write-Host "Mise a jour des redirect URIs..." -ForegroundColor Yellow

    # Nouveaux redirect URIs pour l'application JSF
    $newRedirectUris = @(
        "http://localhost:8081/*",
        "http://localhost:8081/",
        "http://localhost:8081/dashboard.xhtml",
        "http://localhost:8081/index.xhtml",
        "http://localhost:3000/*",
        "http://localhost:3000/",
        "http://localhost:3000/dashboard",
        "http://localhost:3001/*",
        "http://localhost:3001/",
        "http://localhost:3001/dashboard",
        "https://btpxpress.lions.dev/*",
        "https://btpxpress.lions.dev/",
        "https://btpxpress.lions.dev/dashboard",
        "https://btpxpress.lions.dev/dashboard.xhtml"
    )

    $newWebOrigins = @(
        "http://localhost:8081",
        "http://localhost:3000",
        "http://localhost:3001",
        "https://btpxpress.lions.dev"
    )

    # Mettre a jour la configuration du client
    $Client.redirectUris = $newRedirectUris
    $Client.webOrigins = $newWebOrigins
    $Client.publicClient = $true
    $Client.standardFlowEnabled = $true
    $Client.implicitFlowEnabled = $false
    $Client.directAccessGrantsEnabled = $true
    $Client.serviceAccountsEnabled = $false

    # Activer PKCE
    if (-not $Client.attributes) {
        $Client.attributes = @{}
    }
    $Client.attributes."pkce.code.challenge.method" = "S256"
    $Client.attributes."post.logout.redirect.uris" = "http://localhost:8081/*##http://localhost:3000/*##https://btpxpress.lions.dev/*"

    $headers = @{
        Authorization = "Bearer $Token"
        "Content-Type" = "application/json"
    }

    $body = $Client | ConvertTo-Json -Depth 10

    try {
        Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/clients/$($Client.id)" `
            -Method Put `
            -Headers $headers `
            -Body $body | Out-Null

        Write-Host "Redirect URIs mis a jour:" -ForegroundColor Green
        $newRedirectUris | ForEach-Object { Write-Host "   - $_" -ForegroundColor Cyan }

        Write-Host ""
        Write-Host "Web Origins mis a jour:" -ForegroundColor Green
        $newWebOrigins | ForEach-Object { Write-Host "   - $_" -ForegroundColor Cyan }
    }
    catch {
        Write-Host "Erreur lors de la mise a jour: $_" -ForegroundColor Red
        Write-Host $_.Exception.Message -ForegroundColor Red
        exit 1
    }
}

# Fonction pour creer un utilisateur de test
function Create-TestUser {
    param([string]$Token)

    Write-Host ""
    Write-Host "Creation d'un utilisateur de test..." -ForegroundColor Yellow

    $headers = @{
        Authorization = "Bearer $Token"
        "Content-Type" = "application/json"
    }

    # Verifier si l'utilisateur existe deja
    try {
        $users = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users?username=test@btpxpress.com" `
            -Method Get `
            -Headers $headers

        if ($users.Count -gt 0) {
            Write-Host "L'utilisateur test@btpxpress.com existe deja" -ForegroundColor Cyan
            return $users[0]
        }
    }
    catch {
        # Utilisateur n'existe pas, on va le creer
    }

    # Creer l'utilisateur
    $newUser = @{
        username = "test@btpxpress.com"
        email = "test@btpxpress.com"
        firstName = "Test"
        lastName = "BTPXpress"
        enabled = $true
        emailVerified = $true
        credentials = @(
            @{
                type = "password"
                value = "Test123!"
                temporary = $false
            }
        )
    } | ConvertTo-Json -Depth 10

    try {
        Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users" `
            -Method Post `
            -Headers $headers `
            -Body $newUser | Out-Null

        Write-Host "Utilisateur de test cree:" -ForegroundColor Green
        Write-Host "   Email: test@btpxpress.com" -ForegroundColor Cyan
        Write-Host "   Mot de passe: Test123!" -ForegroundColor Cyan

        # Recuperer l'utilisateur cree
        $users = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users?username=test@btpxpress.com" `
            -Method Get `
            -Headers $headers

        # Assigner le role btpxpress_user ou admin
        if ($users.Count -gt 0) {
            $userId = $users[0].id

            # Recuperer les roles disponibles
            $roles = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/roles" `
                -Method Get `
                -Headers $headers

            $userRole = $roles | Where-Object { $_.name -eq "admin" }

            if ($userRole) {
                $roleAssignment = @($userRole) | ConvertTo-Json -Depth 10 -AsArray

                Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users/$userId/role-mappings/realm" `
                    -Method Post `
                    -Headers $headers `
                    -Body $roleAssignment | Out-Null

                Write-Host "Role admin assigne a l'utilisateur" -ForegroundColor Green
            }
        }
    }
    catch {
        Write-Host "Erreur lors de la creation de l'utilisateur: $_" -ForegroundColor Yellow
        Write-Host $_.Exception.Message -ForegroundColor Yellow
    }
}

# Execution principale
Write-Host ""
Write-Host "Debut de la configuration..." -ForegroundColor Green

$token = Get-AdminToken
$client = Get-ClientConfig -Token $token
Update-ClientRedirectUris -Token $token -Client $client
Create-TestUser -Token $token

Write-Host ""
Write-Host "Configuration terminee avec succes!" -ForegroundColor Green
Write-Host ""
Write-Host "Prochaines etapes:" -ForegroundColor Yellow
Write-Host "1. Demarrer l'application: mvn quarkus:dev" -ForegroundColor Cyan
Write-Host "2. Acceder a http://localhost:8081" -ForegroundColor Cyan
Write-Host "3. Se connecter avec: test@btpxpress.com / Test123!" -ForegroundColor Cyan
