#!/bin/bash

set -e

echo "============================================================================="
echo "🚀 CONFIGURATION SIMPLE UNIONFLOW KEYCLOAK"
echo "============================================================================="

# Configuration
KEYCLOAK_URL="http://192.168.1.145:8180"
REALM="unionflow"
ADMIN_USER="admin"
ADMIN_PASSWORD="admin"

# Obtenir le token admin
echo "1. Obtention du token admin..."
TOKEN_RESPONSE=$(curl -s -X POST \
    "${KEYCLOAK_URL}/realms/master/protocol/openid-connect/token" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d "username=${ADMIN_USER}&password=${ADMIN_PASSWORD}&grant_type=password&client_id=admin-cli")

TOKEN=$(echo "$TOKEN_RESPONSE" | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
    echo "ERREUR: Impossible d'obtenir le token"
    exit 1
fi

echo "✓ Token obtenu"

# Créer les rôles
echo ""
echo "2. Création des rôles..."

declare -A ROLES=(
    ["SUPER_ADMINISTRATEUR"]="100"
    ["ADMINISTRATEUR_ORGANISATION"]="85"
    ["RESPONSABLE_TECHNIQUE"]="80"
    ["RESPONSABLE_FINANCIER"]="75"
    ["RESPONSABLE_MEMBRES"]="70"
    ["MEMBRE_ACTIF"]="50"
    ["MEMBRE_SIMPLE"]="30"
    ["VISITEUR"]="0"
)

for role_name in "${!ROLES[@]}"; do
    level="${ROLES[$role_name]}"
    echo -n "  Création $role_name... "
    
    ROLE_DATA="{\"name\":\"$role_name\",\"description\":\"$role_name - Niveau $level\",\"attributes\":{\"level\":[\"$level\"]}}"
    
    HTTP_CODE=$(curl -s -w "%{http_code}" -X POST \
        "${KEYCLOAK_URL}/admin/realms/${REALM}/roles" \
        -H "Authorization: Bearer ${TOKEN}" \
        -H "Content-Type: application/json" \
        -d "$ROLE_DATA")
    
    CODE="${HTTP_CODE: -3}"
    
    if [ "$CODE" = "201" ]; then
        echo "✓"
    elif [ "$CODE" = "409" ]; then
        echo "✓ (existe déjà)"
    else
        echo "✗ (code: $CODE)"
    fi
done

# Créer les utilisateurs
echo ""
echo "3. Création des utilisateurs..."

declare -A USERS=(
    ["superadmin"]="superadmin@unionflow.dev:SuperAdmin123!:Super:Admin:SUPER_ADMINISTRATEUR"
    ["admin.org"]="admin@association-dev.fr:AdminOrg123!:Admin:Organisation:ADMINISTRATEUR_ORGANISATION"
    ["tech.lead"]="tech@association-dev.fr:TechLead123!:Tech:Lead:RESPONSABLE_TECHNIQUE"
    ["tresorier"]="tresorier@association-dev.fr:Tresorier123!:Tresorier:Finance:RESPONSABLE_FINANCIER"
    ["rh.manager"]="rh@association-dev.fr:RhManager123!:RH:Manager:RESPONSABLE_MEMBRES"
    ["marie.active"]="marie@association-dev.fr:Marie123!:Marie:Active:MEMBRE_ACTIF"
    ["jean.simple"]="jean@association-dev.fr:Jean123!:Jean:Simple:MEMBRE_SIMPLE"
    ["visiteur"]="visiteur@example.com:Visiteur123!:Visiteur:Public:VISITEUR"
)

for username in "${!USERS[@]}"; do
    IFS=':' read -r email password firstname lastname role <<< "${USERS[$username]}"
    
    echo -n "  Création $username... "
    
    USER_DATA="{\"username\":\"$username\",\"email\":\"$email\",\"firstName\":\"$firstname\",\"lastName\":\"$lastname\",\"enabled\":true,\"emailVerified\":true,\"credentials\":[{\"type\":\"password\",\"value\":\"$password\",\"temporary\":false}]}"
    
    HTTP_CODE=$(curl -s -w "%{http_code}" -X POST \
        "${KEYCLOAK_URL}/admin/realms/${REALM}/users" \
        -H "Authorization: Bearer ${TOKEN}" \
        -H "Content-Type: application/json" \
        -d "$USER_DATA")
    
    CODE="${HTTP_CODE: -3}"
    
    if [ "$CODE" = "201" ]; then
        echo "✓"
        
        # Assigner le rôle
        sleep 1
        
        # Obtenir l'ID utilisateur
        USER_SEARCH=$(curl -s -X GET \
            "${KEYCLOAK_URL}/admin/realms/${REALM}/users?username=${username}" \
            -H "Authorization: Bearer ${TOKEN}")
        
        USER_ID=$(echo "$USER_SEARCH" | grep -o '"id":"[^"]*' | head -1 | cut -d'"' -f4)
        
        if [ -n "$USER_ID" ]; then
            # Obtenir le rôle
            ROLE_INFO=$(curl -s -X GET \
                "${KEYCLOAK_URL}/admin/realms/${REALM}/roles/${role}" \
                -H "Authorization: Bearer ${TOKEN}")
            
            ROLE_ID=$(echo "$ROLE_INFO" | grep -o '"id":"[^"]*' | cut -d'"' -f4)
            
            if [ -n "$ROLE_ID" ]; then
                ROLE_ASSIGNMENT="[{\"id\":\"$ROLE_ID\",\"name\":\"$role\"}]"
                
                curl -s -X POST \
                    "${KEYCLOAK_URL}/admin/realms/${REALM}/users/${USER_ID}/role-mappings/realm" \
                    -H "Authorization: Bearer ${TOKEN}" \
                    -H "Content-Type: application/json" \
                    -d "$ROLE_ASSIGNMENT" > /dev/null
                
                echo "    → Rôle $role assigné"
            fi
        fi
        
    elif [ "$CODE" = "409" ]; then
        echo "✓ (existe déjà)"
    else
        echo "✗ (code: $CODE)"
    fi
done

echo ""
echo "4. Test d'authentification..."

# Tester avec marie.active
AUTH_RESPONSE=$(curl -s -X POST \
    "${KEYCLOAK_URL}/realms/${REALM}/protocol/openid-connect/token" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d "username=marie.active&password=Marie123!&grant_type=password&client_id=unionflow-mobile")

if echo "$AUTH_RESPONSE" | grep -q "access_token"; then
    echo "✓ Test authentification marie.active réussi"
    
    # Obtenir les infos utilisateur
    ACCESS_TOKEN=$(echo "$AUTH_RESPONSE" | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)
    
    USER_INFO=$(curl -s -X GET \
        "${KEYCLOAK_URL}/realms/${REALM}/protocol/openid-connect/userinfo" \
        -H "Authorization: Bearer ${ACCESS_TOKEN}")
    
    if echo "$USER_INFO" | grep -q "email"; then
        EMAIL=$(echo "$USER_INFO" | grep -o '"email":"[^"]*' | cut -d'"' -f4)
        echo "  → Email: $EMAIL"
    fi
else
    echo "✗ Test authentification échoué"
    echo "  Réponse: ${AUTH_RESPONSE:0:100}..."
fi

echo ""
echo "============================================================================="
echo "✅ CONFIGURATION TERMINÉE"
echo "============================================================================="
echo ""
echo "🔐 COMPTES CRÉÉS :"
echo "• marie.active / Marie123! (MEMBRE_ACTIF)"
echo "• superadmin / SuperAdmin123! (SUPER_ADMINISTRATEUR)"
echo "• jean.simple / Jean123! (MEMBRE_SIMPLE)"
echo "• tech.lead / TechLead123! (RESPONSABLE_TECHNIQUE)"
echo "• rh.manager / RhManager123! (RESPONSABLE_MEMBRES)"
echo "• admin.org / AdminOrg123! (ADMINISTRATEUR_ORGANISATION)"
echo "• tresorier / Tresorier123! (RESPONSABLE_FINANCIER)"
echo "• visiteur / Visiteur123! (VISITEUR)"
echo ""
echo "🚀 TESTEZ MAINTENANT L'APPLICATION MOBILE !"
echo "   Utilisez: marie.active / Marie123!"
echo ""
