# Script pour assigner le role admin a l'utilisateur test

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

Write-Host "Assignation du role admin..." -ForegroundColor Yellow

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

$tokenResponse = Invoke-RestMethod -Uri "$KEYCLOAK_URL/realms/master/protocol/openid-connect/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body
$token = $tokenResponse.access_token

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

# Trouver l'utilisateur
Write-Host "Recherche de l'utilisateur test@btpxpress.com..." -ForegroundColor Yellow
$users = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users?username=test@btpxpress.com" -Method Get -Headers $headers

if ($users.Count -eq 0) {
    Write-Host "Utilisateur non trouve!" -ForegroundColor Red
    exit 1
}

$userId = $users[0].id
Write-Host "Utilisateur trouve: $userId" -ForegroundColor Green

# Recuperer le role admin
Write-Host "Recuperation du role admin..." -ForegroundColor Yellow
$roles = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/roles" -Method Get -Headers $headers
$adminRole = $roles | Where-Object { $_.name -eq "admin" }

if (-not $adminRole) {
    Write-Host "Role admin non trouve!" -ForegroundColor Red
    exit 1
}

Write-Host "Role trouve: $($adminRole.name)" -ForegroundColor Green

# Creer le tableau de roles au bon format
$roleArray = @(
    @{
        id = $adminRole.id
        name = $adminRole.name
    }
)

$roleBody = $roleArray | ConvertTo-Json -Depth 10

Write-Host "JSON a envoyer:" -ForegroundColor Cyan
Write-Host $roleBody -ForegroundColor Cyan

# Assigner le role
try {
    Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users/$userId/role-mappings/realm" `
        -Method Post `
        -Headers $headers `
        -Body $roleBody `
        -ContentType "application/json" | Out-Null

    Write-Host ""
    Write-Host "Role admin assigne avec succes a test@btpxpress.com!" -ForegroundColor Green
}
catch {
    Write-Host "Erreur lors de l'assignation: $_" -ForegroundColor Red
    Write-Host "Le role est peut-etre deja assigne" -ForegroundColor Yellow
}
