#!/bin/bash

# Script de configuration Keycloak pour lions-user-manager
# Configuration CORRECTE avec realm dédié et client uniquement pour le frontend

KEYCLOAK_URL="http://localhost:8180"
MASTER_REALM="master"
APP_REALM="lions-user-manager"
ADMIN_USER="admin"
ADMIN_PASS="admin"

echo "=== Configuration Keycloak pour lions-user-manager ==="
echo ""

# 1. Obtenir le token d'administration
echo "1. Connexion à Keycloak (realm master)..."
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}" \
  -d "password=${ADMIN_PASS}" \
  -d "grant_type=password" \
  -d "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 d'accès"
  exit 1
fi
echo "✅ Connexion réussie"

# 2. Créer le realm dédié pour l'application
echo ""
echo "2. Création du realm dédié '${APP_REALM}'..."
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "${KEYCLOAK_URL}/admin/realms" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{
    \"realm\": \"${APP_REALM}\",
    \"displayName\": \"Lions User Manager\",
    \"enabled\": true,
    \"sslRequired\": \"none\",
    \"registrationAllowed\": false,
    \"loginWithEmailAllowed\": true,
    \"duplicateEmailsAllowed\": false,
    \"resetPasswordAllowed\": true,
    \"editUsernameAllowed\": false,
    \"bruteForceProtected\": true,
    \"accessTokenLifespan\": 3600,
    \"ssoSessionIdleTimeout\": 1800,
    \"ssoSessionMaxLifespan\": 36000
  }")

HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
if [ "$HTTP_CODE" == "201" ] || [ "$HTTP_CODE" == "409" ]; then
  echo "✅ Realm '${APP_REALM}' créé ou existe déjà"
else
  echo "⚠️  Statut HTTP: $HTTP_CODE"
fi

# 3. Créer UNIQUEMENT le client frontend
echo ""
echo "3. Création du client frontend 'lions-user-manager-client'..."
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "${KEYCLOAK_URL}/admin/realms/${APP_REALM}/clients" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "clientId": "lions-user-manager-client",
    "name": "Lions User Manager Client",
    "description": "Interface web pour la gestion des utilisateurs",
    "enabled": true,
    "protocol": "openid-connect",
    "publicClient": false,
    "standardFlowEnabled": true,
    "implicitFlowEnabled": false,
    "directAccessGrantsEnabled": true,
    "serviceAccountsEnabled": false,
    "authorizationServicesEnabled": false,
    "secret": "client-secret-lions-2025",
    "redirectUris": [
      "http://localhost:8080/*",
      "http://localhost:8081/*"
    ],
    "webOrigins": ["*"],
    "attributes": {
      "access.token.lifespan": "3600",
      "pkce.code.challenge.method": "S256"
    }
  }')

HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
if [ "$HTTP_CODE" == "201" ] || [ "$HTTP_CODE" == "409" ]; then
  echo "✅ Client frontend créé ou existe déjà"
else
  echo "⚠️  Statut HTTP: $HTTP_CODE"
fi

# 4. Créer les rôles realm dans le nouveau realm
echo ""
echo "4. Création des rôles dans le realm '${APP_REALM}'..."
for role in admin user_manager user_viewer auditor sync_manager; do
  curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${APP_REALM}/roles" \
    -H "Authorization: Bearer ${TOKEN}" \
    -H "Content-Type: application/json" \
    -d "{\"name\": \"${role}\", \"description\": \"Rôle ${role}\"}" > /dev/null 2>&1
  echo "  ✅ Rôle '${role}' créé"
done

# 5. Créer un utilisateur de test dans le nouveau realm
echo ""
echo "5. Création d'un utilisateur de test dans le realm '${APP_REALM}'..."
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "${KEYCLOAK_URL}/admin/realms/${APP_REALM}/users" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "testuser",
    "email": "test@lions.dev",
    "firstName": "Test",
    "lastName": "User",
    "enabled": true,
    "emailVerified": true,
    "credentials": [{
      "type": "password",
      "value": "test123",
      "temporary": false
    }]
  }')

HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
if [ "$HTTP_CODE" == "201" ] || [ "$HTTP_CODE" == "409" ]; then
  echo "✅ Utilisateur 'testuser' créé (mot de passe: test123)"
else
  echo "⚠️  Statut HTTP: $HTTP_CODE"
fi

# 6. Récupérer et attribuer les rôles
echo ""
echo "6. Attribution des rôles à l'utilisateur..."
USER_RESPONSE=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${APP_REALM}/users?username=testuser" \
  -H "Authorization: Bearer ${TOKEN}")

USER_ID=$(echo "$USER_RESPONSE" | grep -o '"id":"[^"]*' | head -1 | cut -d'"' -f4)

if [ -n "$USER_ID" ]; then
  for role in admin user_manager; do
    ROLE_DATA=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${APP_REALM}/roles/${role}" \
      -H "Authorization: Bearer ${TOKEN}")

    curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${APP_REALM}/users/${USER_ID}/role-mappings/realm" \
      -H "Authorization: Bearer ${TOKEN}" \
      -H "Content-Type: application/json" \
      -d "[${ROLE_DATA}]" > /dev/null 2>&1

    echo "  ✅ Rôle '${role}' attribué à testuser"
  done
fi

echo ""
echo "=== Configuration terminée ==="
echo ""
echo "📋 Récapitulatif:"
echo "  • Realm dédié: ${APP_REALM}"
echo "  • Client Frontend: client_id=lions-user-manager-client, secret=client-secret-lions-2025"
echo "  • Backend: Utilise directement l'Admin API avec admin/admin (pas de client séparé)"
echo "  • Utilisateur de test: testuser / test123"
echo "  • Rôles créés: admin, user_manager, user_viewer, auditor, sync_manager"
echo ""
echo "🌐 Accès:"
echo "  • Backend: http://localhost:8081"
echo "  • Frontend: http://localhost:8080"
echo "  • Keycloak: http://localhost:8180"
echo "  • Admin Console: http://localhost:8180/admin (admin/admin)"
echo ""
echo "⚙️  Prochaines étapes:"
echo "  1. Mettre à jour application-dev.properties avec realm=${APP_REALM}"
echo "  2. Redémarrer les applications"
echo ""
