#!/bin/bash

# Script de configuration Keycloak pour corriger l'authentification frontend
set -e

KEYCLOAK_URL="http://localhost:8180"
REALM="lions-user-manager"
CLIENT_ID="lions-user-manager-client"
CLIENT_SECRET="client-secret-lions-2025"

echo "=========================================="
echo "Configuration Keycloak pour Frontend"
echo "=========================================="

# 1. Obtenir le token admin
echo "1. Récupération du token admin..."
TOKEN=$(curl -s -X POST "${KEYCLOAK_URL}/realms/master/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=admin" \
  -d "password=admin" \
  -d "grant_type=password" \
  -d "client_id=admin-cli" | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
  echo "❌ Erreur: Impossible d'obtenir le token admin"
  exit 1
fi
echo "✅ Token obtenu"

# 2. Vérifier si le client existe
echo ""
echo "2. Vérification du client ${CLIENT_ID}..."
CLIENTS=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/clients" \
  -H "Authorization: Bearer ${TOKEN}")

# Extraire l'ID interne du client
INTERNAL_CLIENT_ID=$(echo "$CLIENTS" | grep -B 5 "\"clientId\":\"${CLIENT_ID}\"" | grep '"id"' | head -1 | grep -o '"id":"[^"]*' | cut -d'"' -f4)

if [ -z "$INTERNAL_CLIENT_ID" ]; then
  echo "⚠️ Client ${CLIENT_ID} n'existe pas, création..."

  # Créer le client
  curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${REALM}/clients" \
    -H "Authorization: Bearer ${TOKEN}" \
    -H "Content-Type: application/json" \
    -d "{
      \"clientId\": \"${CLIENT_ID}\",
      \"enabled\": true,
      \"protocol\": \"openid-connect\",
      \"publicClient\": false,
      \"secret\": \"${CLIENT_SECRET}\",
      \"redirectUris\": [\"http://localhost:8080/*\"],
      \"webOrigins\": [\"http://localhost:8080\"],
      \"standardFlowEnabled\": true,
      \"directAccessGrantsEnabled\": true,
      \"serviceAccountsEnabled\": false,
      \"implicitFlowEnabled\": false,
      \"fullScopeAllowed\": true
    }"

  echo "✅ Client créé"

  # Récupérer l'ID après création
  CLIENTS=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/clients" \
    -H "Authorization: Bearer ${TOKEN}")
  INTERNAL_CLIENT_ID=$(echo "$CLIENTS" | grep -B 5 "\"clientId\":\"${CLIENT_ID}\"" | grep '"id"' | head -1 | grep -o '"id":"[^"]*' | cut -d'"' -f4)
else
  echo "✅ Client existe (ID: ${INTERNAL_CLIENT_ID})"
fi

# 3. Mettre à jour la configuration du client
echo ""
echo "3. Mise à jour de la configuration du client..."
curl -s -X PUT "${KEYCLOAK_URL}/admin/realms/${REALM}/clients/${INTERNAL_CLIENT_ID}" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{
    \"clientId\": \"${CLIENT_ID}\",
    \"enabled\": true,
    \"protocol\": \"openid-connect\",
    \"publicClient\": false,
    \"redirectUris\": [\"http://localhost:8080/*\"],
    \"webOrigins\": [\"+\"],
    \"standardFlowEnabled\": true,
    \"directAccessGrantsEnabled\": true,
    \"serviceAccountsEnabled\": false,
    \"implicitFlowEnabled\": false,
    \"fullScopeAllowed\": true,
    \"attributes\": {
      \"access.token.lifespan\": \"3600\",
      \"use.refresh.tokens\": \"true\"
    }
  }"

echo "✅ Configuration mise à jour"

# 4. Définir le secret du client
echo ""
echo "4. Configuration du secret client..."
curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${REALM}/clients/${INTERNAL_CLIENT_ID}/client-secret" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{\"value\": \"${CLIENT_SECRET}\"}"

echo "✅ Secret configuré"

# 5. Vérifier les utilisateurs
echo ""
echo "5. Vérification des utilisateurs..."
USERS=$(curl -s -X GET "${KEYCLOAK_URL}/admin/realms/${REALM}/users" \
  -H "Authorization: Bearer ${TOKEN}")

USER_COUNT=$(echo "$USERS" | grep -c '"username"' || echo "0")
echo "✅ Utilisateurs trouvés: ${USER_COUNT}"

if [ "$USER_COUNT" -eq "0" ]; then
  echo "⚠️ Aucun utilisateur trouvé, création de testuser..."

  # Créer l'utilisateur testuser
  curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${REALM}/users" \
    -H "Authorization: Bearer ${TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{
      "username": "testuser",
      "enabled": true,
      "emailVerified": true,
      "firstName": "Test",
      "lastName": "User",
      "email": "testuser@lions.dev",
      "credentials": [{
        "type": "password",
        "value": "test123",
        "temporary": false
      }]
    }'

  echo "✅ Utilisateur testuser créé"
fi

echo ""
echo "=========================================="
echo "✅ Configuration Keycloak terminée!"
echo "=========================================="
echo ""
echo "Informations de connexion:"
echo "  Realm: ${REALM}"
echo "  Client ID: ${CLIENT_ID}"
echo "  Client Secret: ${CLIENT_SECRET}"
echo "  Test User: testuser / test123"
echo ""
echo "URLs:"
echo "  Frontend: http://localhost:8080"
echo "  Backend: http://localhost:8081"
echo "  Keycloak: http://localhost:8180"
echo ""
