# Script PowerShell pour appliquer la sécurisation automatique aux pages XHTML
# Usage: .\apply-page-security.ps1

$ErrorActionPreference = "Stop"

# Mapping des chemins de pages vers leurs rôles autorisés
$pageSecurityMap = @{
    # Super Admin
    "super-admin/dashboard.xhtml" = "SUPER_ADMIN"
    "super-admin/dashboard-enhanced.xhtml" = "SUPER_ADMIN"
    "super-admin/entites/gestion-enhanced.xhtml" = "SUPER_ADMIN"
    "super-admin/roles/gestion.xhtml" = "SUPER_ADMIN"
    "super-admin/types/organisations.xhtml" = "SUPER_ADMIN"

    # Admin Organisation
    "admin/audit.xhtml" = "ADMIN,SUPER_ADMIN"
    "admin/backup.xhtml" = "ADMIN,SUPER_ADMIN"
    "admin/settings.xhtml" = "ADMIN,SUPER_ADMIN"
    "admin/users.xhtml" = "ADMIN,SUPER_ADMIN"
    "secure/admin/utilisateurs.xhtml" = "ADMIN,SUPER_ADMIN"
    "secure/admin/audit.xhtml" = "ADMIN,SUPER_ADMIN"
    "secure/admin/parametres.xhtml" = "ADMIN,SUPER_ADMIN"
    "secure/admin/roles.xhtml" = "ADMIN,SUPER_ADMIN"
    "admin/audit/journal.xhtml" = "ADMIN,SUPER_ADMIN"

    # Gestion des membres
    "secure/membre/inscription.xhtml" = "SECRETAIRE,ADMIN"
    "secure/membre/recherche.xhtml" = "SECRETAIRE,TRESORIER,RESPONSABLE_SOCIAL,RESPONSABLE_EVENEMENTS,ADMIN"
    "secure/membre/profil.xhtml" = "SECRETAIRE,ADMIN"
    "secure/membre/import.xhtml" = "SECRETAIRE,ADMIN"
    "secure/membre/export.xhtml" = "SECRETAIRE,TRESORIER,ADMIN"
    "secure/membre/cotisations.xhtml" = "TRESORIER,SECRETAIRE,ADMIN"

    # Gestion financière
    "admin/finance/caisse.xhtml" = "TRESORIER,ADMIN"
    "secure/finance/tresorerie.xhtml" = "TRESORIER,ADMIN"
    "secure/finance/budgets.xhtml" = "TRESORIER,ADMIN"
    "secure/finance/bilans.xhtml" = "TRESORIER,ADMIN"
    "secure/comptabilite/gestion.xhtml" = "TRESORIER,ADMIN"
    "admin/cotisations/gestion.xhtml" = "TRESORIER,SECRETAIRE,ADMIN"
    "secure/cotisation/collect.xhtml" = "TRESORIER,ADMIN"
    "secure/cotisation/paiement.xhtml" = "TRESORIER,SECRETAIRE,ADMIN"
    "secure/cotisation/reminders.xhtml" = "TRESORIER,SECRETAIRE,ADMIN"
    "secure/cotisation/report.xhtml" = "TRESORIER,ADMIN"
    "secure/cotisation/rapports.xhtml" = "TRESORIER,ADMIN"

    # Gestion des événements
    "admin/evenements/liste.xhtml" = "RESPONSABLE_EVENEMENTS,SECRETAIRE,ADMIN"
    "admin/evenements/creation.xhtml" = "RESPONSABLE_EVENEMENTS,SECRETAIRE,ADMIN"
    "admin/evenements/gestion.xhtml" = "RESPONSABLE_EVENEMENTS,SECRETAIRE,ADMIN"
    "admin/evenements/participants.xhtml" = "RESPONSABLE_EVENEMENTS,SECRETAIRE,ADMIN"
    "secure/evenement/creation.xhtml" = "RESPONSABLE_EVENEMENTS,SECRETAIRE,ADMIN"
    "secure/evenement/gestion.xhtml" = "RESPONSABLE_EVENEMENTS,SECRETAIRE,ADMIN"
    "secure/evenement/create.xhtml" = "RESPONSABLE_EVENEMENTS,SECRETAIRE,ADMIN"
    "secure/evenement/planification.xhtml" = "RESPONSABLE_EVENEMENTS,ADMIN"
    "secure/evenement/logistique.xhtml" = "RESPONSABLE_EVENEMENTS,ADMIN"
    "secure/evenement/bilan.xhtml" = "RESPONSABLE_EVENEMENTS,SECRETAIRE,ADMIN"
    "secure/evenement/reservations.xhtml" = "RESPONSABLE_EVENEMENTS,ADMIN"
    "secure/evenement/participants.xhtml" = "RESPONSABLE_EVENEMENTS,SECRETAIRE,ADMIN"
    "secure/evenement/calendar.xhtml" = "ALL"
    "secure/evenement/calendrier.xhtml" = "ALL"
    "secure/evenement/participation.xhtml" = "ALL"

    # Gestion des aides sociales
    "admin/aides/gestion.xhtml" = "RESPONSABLE_SOCIAL,ADMIN"
    "admin/demandes/gestion.xhtml" = "RESPONSABLE_SOCIAL,ADMIN"
    "admin/demandes/aide-sociale.xhtml" = "RESPONSABLE_SOCIAL,ADMIN"
    "secure/aide/demande.xhtml" = "ALL"
    "secure/aide/statistiques.xhtml" = "RESPONSABLE_SOCIAL,ADMIN"
    "secure/aide/historique.xhtml" = "ALL"

    # Adhésions
    "secure/adhesion/liste.xhtml" = "SECRETAIRE,ADMIN"
    "secure/adhesion/demande.xhtml" = "ALL"
    "secure/adhesion/new.xhtml" = "SECRETAIRE,ADMIN"
    "secure/adhesion/renouvellement.xhtml" = "ALL"
    "secure/adhesion/validation.xhtml" = "SECRETAIRE,ADMIN"
    "secure/adhesion/history.xhtml" = "SECRETAIRE,ADMIN"
    "secure/adhesion/historique.xhtml" = "ALL"
    "secure/adhesion/pending.xhtml" = "SECRETAIRE,ADMIN"
    "secure/adhesion/cartes-membres.xhtml" = "SECRETAIRE,ADMIN"

    # Rapports
    "secure/reports.xhtml" = "TRESORIER,SECRETAIRE,ADMIN"
    "secure/rapport/details.xhtml" = "TRESORIER,SECRETAIRE,ADMIN"
    "secure/rapport/export.xhtml" = "TRESORIER,SECRETAIRE,ADMIN"
    "secure/rapport/activites.xhtml" = "SECRETAIRE,ADMIN"
    "secure/rapport/finances.xhtml" = "TRESORIER,ADMIN"
    "secure/rapport/membres.xhtml" = "SECRETAIRE,ADMIN"
    "secure/rapport/tableaux-bord.xhtml" = "TRESORIER,SECRETAIRE,ADMIN"
    "admin/rapports/finances.xhtml" = "TRESORIER,ADMIN"
    "admin/rapports/statistiques.xhtml" = "ADMIN"

    # Pages personnelles
    "secure/profile.xhtml" = "ALL"
    "secure/personnel/profil.xhtml" = "ALL"
    "secure/personnel/activites.xhtml" = "ALL"
    "secure/personnel/agenda.xhtml" = "ALL"
    "secure/personnel/documents.xhtml" = "ALL"
    "secure/personnel/notifications.xhtml" = "ALL"
    "secure/personnel/preferences.xhtml" = "ALL"
    "secure/personnel/favoris.xhtml" = "ALL"
    "secure/personnel/parametres.xhtml" = "ALL"
    "membre/cotisations.xhtml" = "ALL"
    "membre/dashboard.xhtml" = "MEMBRE_ACTIF"

    # Aide et support
    "secure/aide/faq.xhtml" = "ALL"
    "secure/aide/guide.xhtml" = "ALL"
    "secure/aide/support.xhtml" = "ALL"
    "secure/aide/tutoriels.xhtml" = "ALL"
    "secure/aide/nouveautes.xhtml" = "ALL"
    "secure/aide/apropos.xhtml" = "ALL"
    "secure/aide/documentation.xhtml" = "ALL"
    "secure/aide/suggestions.xhtml" = "ALL"
    "secure/aide/tickets.xhtml" = "ALL"

    # Communication
    "secure/communication/notifications.xhtml" = "SECRETAIRE,ADMIN"

    # Documents
    "admin/documents/gestion.xhtml" = "SECRETAIRE,ADMIN"
    "secure/documents/mes-documents.xhtml" = "ALL"

    # Utilitaires
    "secure/outils/exports-masse.xhtml" = "TRESORIER,SECRETAIRE,ADMIN"
    "secure/stats.xhtml" = "ADMIN"
    "secure/souscription/dashboard.xhtml" = "ADMIN"
}

$basePath = "C:\Users\dadyo\PersonalProjects\lions-workspace\unionflow\unionflow-client-quarkus-primefaces-freya\src\main\resources\META-INF\resources\pages"

$securityComponent = @"
    <!-- Sécurisation de la page basée sur les rôles -->
    <ui:include src="/templates/components/security/page-access-control.xhtml">
        <ui:param name="allowedRoles" value="__ROLES__" />
    </ui:include>

"@

$processedCount = 0
$skippedCount = 0
$errorCount = 0

Write-Host "============================================" -ForegroundColor Cyan
Write-Host "  Application de la Sécurisation des Pages" -ForegroundColor Cyan
Write-Host "============================================" -ForegroundColor Cyan
Write-Host ""

foreach ($page in $pageSecurityMap.Keys) {
    $filePath = Join-Path $basePath $page
    $roles = $pageSecurityMap[$page]

    if (-not (Test-Path $filePath)) {
        Write-Host "[SKIP] $page (fichier introuvable)" -ForegroundColor Yellow
        $skippedCount++
        continue
    }

    try {
        $content = Get-Content $filePath -Raw -Encoding UTF8

        # Vérifier si la sécurité est déjà appliquée
        if ($content -match "page-access-control\.xhtml") {
            Write-Host "[SKIP] $page (déjà sécurisée)" -ForegroundColor Gray
            $skippedCount++
            continue
        }

        # Insérer le composant de sécurité après <ui:composition> ou <ui:define name="content">
        $securityBlock = $securityComponent -replace "__ROLES__", $roles

        if ($content -match '<ui:composition[^>]*>') {
            $content = $content -replace '(<ui:composition[^>]*>)', "`$1`n$securityBlock"
        }
        elseif ($content -match '<ui:define name="content">') {
            $content = $content -replace '(<ui:define name="content">)', "`$1`n$securityBlock"
        }
        else {
            Write-Host "[ERROR] $page (impossible de trouver le point d'insertion)" -ForegroundColor Red
            $errorCount++
            continue
        }

        # Sauvegarder le fichier
        Set-Content -Path $filePath -Value $content -Encoding UTF8 -NoNewline

        Write-Host "[OK] $page → Rôles: $roles" -ForegroundColor Green
        $processedCount++
    }
    catch {
        Write-Host "[ERROR] $page : $_" -ForegroundColor Red
        $errorCount++
    }
}

Write-Host ""
Write-Host "============================================" -ForegroundColor Cyan
Write-Host "  Résumé" -ForegroundColor Cyan
Write-Host "============================================" -ForegroundColor Cyan
Write-Host "Pages sécurisées  : $processedCount" -ForegroundColor Green
Write-Host "Pages ignorées    : $skippedCount" -ForegroundColor Yellow
Write-Host "Erreurs           : $errorCount" -ForegroundColor Red
Write-Host ""
Write-Host "✓ Script terminé avec succès!" -ForegroundColor Green
