#!/bin/bash

# Script pour créer et assigner les rôles dans Keycloak
# Usage: ./assign_roles.sh

set -e

KEYCLOAK_URL="http://localhost:8180"
REALM="unionflow"
ADMIN_USER="admin"
ADMIN_PASSWORD="admin"

echo "🎭 Attribution des rôles utilisateurs Keycloak"
echo "=============================================="
echo ""

# 1. 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" \
  -d "password=$ADMIN_PASSWORD" \
  -d "grant_type=password" \
  -d "client_id=admin-cli")

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

if [ -z "$ADMIN_TOKEN" ]; then
  echo "❌ Échec obtention token admin"
  exit 1
fi

echo "✅ Token obtenu"
echo ""

# 2. Créer les rôles realm si nécessaire
echo "2️⃣  Création des rôles realm..."

# Créer ORG_ADMIN
ORG_ADMIN_ROLE='{
  "name": "ORG_ADMIN",
  "description": "Administrator d'\''une organisation"
}'

ORG_ADMIN_CREATE=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
  "$KEYCLOAK_URL/admin/realms/$REALM/roles" \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d "$ORG_ADMIN_ROLE")

if [ "$ORG_ADMIN_CREATE" = "201" ]; then
  echo "✅ Rôle ORG_ADMIN créé"
elif [ "$ORG_ADMIN_CREATE" = "409" ]; then
  echo "⚠️  Rôle ORG_ADMIN existe déjà"
else
  echo "❌ Échec création ORG_ADMIN (HTTP $ORG_ADMIN_CREATE)"
fi

# Créer SUPER_ADMIN
SUPER_ADMIN_ROLE='{
  "name": "SUPER_ADMIN",
  "description": "Super administrateur de la plateforme"
}'

SUPER_ADMIN_CREATE=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
  "$KEYCLOAK_URL/admin/realms/$REALM/roles" \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d "$SUPER_ADMIN_ROLE")

if [ "$SUPER_ADMIN_CREATE" = "201" ]; then
  echo "✅ Rôle SUPER_ADMIN créé"
elif [ "$SUPER_ADMIN_CREATE" = "409" ]; then
  echo "⚠️  Rôle SUPER_ADMIN existe déjà"
else
  echo "❌ Échec création SUPER_ADMIN (HTTP $SUPER_ADMIN_CREATE)"
fi

echo ""

# 3. Récupérer les IDs des utilisateurs
echo "3️⃣  Récupération des IDs utilisateurs..."

ORG_ADMIN_USER_ID=$(curl -s -X GET \
  "$KEYCLOAK_URL/admin/realms/$REALM/users?username=orgadmin@unionflow.test&exact=true" \
  -H "Authorization: Bearer $ADMIN_TOKEN" | grep -o '"id":"[^"]*' | head -1 | cut -d'"' -f4)

SUPER_ADMIN_USER_ID=$(curl -s -X GET \
  "$KEYCLOAK_URL/admin/realms/$REALM/users?username=admin@unionflow.test&exact=true" \
  -H "Authorization: Bearer $ADMIN_TOKEN" | grep -o '"id":"[^"]*' | head -1 | cut -d'"' -f4)

if [ -z "$ORG_ADMIN_USER_ID" ]; then
  echo "❌ Utilisateur orgadmin@unionflow.test non trouvé"
  exit 1
fi

if [ -z "$SUPER_ADMIN_USER_ID" ]; then
  echo "❌ Utilisateur admin@unionflow.test non trouvé"
  exit 1
fi

echo "✅ Utilisateurs trouvés:"
echo "   orgadmin@unionflow.test: $ORG_ADMIN_USER_ID"
echo "   admin@unionflow.test: $SUPER_ADMIN_USER_ID"
echo ""

# 4. Récupérer les définitions des rôles
echo "4️⃣  Récupération des rôles..."

ORG_ADMIN_ROLE_DEF=$(curl -s -X GET \
  "$KEYCLOAK_URL/admin/realms/$REALM/roles/ORG_ADMIN" \
  -H "Authorization: Bearer $ADMIN_TOKEN")

SUPER_ADMIN_ROLE_DEF=$(curl -s -X GET \
  "$KEYCLOAK_URL/admin/realms/$REALM/roles/SUPER_ADMIN" \
  -H "Authorization: Bearer $ADMIN_TOKEN")

echo "✅ Rôles récupérés"
echo ""

# 5. Assigner ORG_ADMIN à orgadmin@unionflow.test
echo "5️⃣  Attribution rôle ORG_ADMIN..."

ASSIGN_ORG_ADMIN=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
  "$KEYCLOAK_URL/admin/realms/$REALM/users/$ORG_ADMIN_USER_ID/role-mappings/realm" \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d "[$ORG_ADMIN_ROLE_DEF]")

if [ "$ASSIGN_ORG_ADMIN" = "204" ]; then
  echo "✅ Rôle ORG_ADMIN assigné à orgadmin@unionflow.test"
else
  echo "⚠️  Attribution ORG_ADMIN (HTTP $ASSIGN_ORG_ADMIN) - possiblement déjà assigné"
fi

echo ""

# 6. Assigner SUPER_ADMIN à admin@unionflow.test
echo "6️⃣  Attribution rôle SUPER_ADMIN..."

ASSIGN_SUPER_ADMIN=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
  "$KEYCLOAK_URL/admin/realms/$REALM/users/$SUPER_ADMIN_USER_ID/role-mappings/realm" \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d "[$SUPER_ADMIN_ROLE_DEF]")

if [ "$ASSIGN_SUPER_ADMIN" = "204" ]; then
  echo "✅ Rôle SUPER_ADMIN assigné à admin@unionflow.test"
else
  echo "⚠️  Attribution SUPER_ADMIN (HTTP $ASSIGN_SUPER_ADMIN) - possiblement déjà assigné"
fi

echo ""
echo "=============================================="
echo "✅ Configuration des rôles terminée!"
echo ""
echo "Vérification:"
echo "  curl -X POST http://localhost:8180/realms/unionflow/protocol/openid-connect/token \\"
echo "    -d 'username=orgadmin@unionflow.test' \\"
echo "    -d 'password=OrgAdmin@123' \\"
echo "    -d 'grant_type=password' \\"
echo "    -d 'client_id=unionflow-mobile'"
echo ""
echo "Prochaine étape:"
echo "  flutter test integration_test/"
echo "=============================================="
