#!/bin/bash

# Script de configuration Keycloak pour lions-user-manager
# Usage: ./setup-keycloak.sh

KEYCLOAK_URL="http://localhost:8180"
REALM="master"
ADMIN_USER="admin"
ADMIN_PASS="admin"

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

# 1. Obtenir le token d'administration
echo "1. Connexion à Keycloak..."
TOKEN=$(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" | jq -r '.access_token')

if [ -z "$TOKEN" ] || [ "$TOKEN" == "null" ]; then
  echo "❌ Erreur: Impossible d'obtenir le token d'accès"
  exit 1
fi
echo "✅ Connexion réussie"

# 2. Créer le client backend (lions-user-manager)
echo ""
echo "2. Création du client backend 'lions-user-manager'..."
curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${REALM}/clients" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "clientId": "lions-user-manager",
    "name": "Lions User Manager Backend",
    "description": "Service backend pour la gestion des utilisateurs",
    "enabled": true,
    "protocol": "openid-connect",
    "publicClient": false,
    "serviceAccountsEnabled": true,
    "standardFlowEnabled": false,
    "implicitFlowEnabled": false,
    "directAccessGrantsEnabled": false,
    "authorizationServicesEnabled": false,
    "secret": "sD8hT13lG6c79WOWQk3dVzya5pfPhzw3",
    "redirectUris": ["http://localhost:8081/*"],
    "webOrigins": ["http://localhost:8081", "http://localhost:8080"],
    "attributes": {
      "access.token.lifespan": "3600"
    }
  }' 2>&1

echo "✅ Client backend créé"

# 3. Créer le client frontend (lions-user-manager-client)
echo ""
echo "3. Création du client frontend 'lions-user-manager-client'..."
curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${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,
    "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"
    }
  }' 2>&1

echo "✅ Client frontend créé"

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

# 5. Créer un utilisateur de test
echo ""
echo "5. Création d'un utilisateur de test..."
curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${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
    }]
  }' 2>&1

echo "✅ Utilisateur 'testuser' créé (mot de passe: test123)"

# 6. Récupérer l'ID de l'utilisateur
USER_ID=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/users?username=testuser" \
  -H "Authorization: Bearer ${TOKEN}" | jq -r '.[0].id')

if [ -n "$USER_ID" ] && [ "$USER_ID" != "null" ]; then
  echo ""
  echo "6. Attribution des rôles à l'utilisateur..."

  # Récupérer les IDs des rôles
  for role in admin user_manager; do
    ROLE_DATA=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/roles/${role}" \
      -H "Authorization: Bearer ${TOKEN}")

    # Attribuer le rôle
    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_DATA}]" 2>&1

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

echo ""
echo "=== Configuration terminée ==="
echo ""
echo "📋 Récapitulatif:"
echo "  • Backend:  client_id=lions-user-manager, secret=sD8hT13lG6c79WOWQk3dVzya5pfPhzw3"
echo "  • Frontend: client_id=lions-user-manager-client, secret=client-secret-lions-2025"
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 ""
