#!/bin/bash
KEYCLOAK_URL="http://localhost:8180"
REALM_NAME="unionflow"
TEST_PASSWORD="Test@123"

# Obtenir le token
TOKEN=$(curl -s -X POST "$KEYCLOAK_URL/realms/master/protocol/openid-connect/token" \
  -d "client_id=admin-cli" -d "username=admin" -d "password=admin" -d "grant_type=password" | \
  grep -o '"access_token":"[^"]*' | cut -d'"' -f4)

echo "Token obtenu, création des utilisateurs manquants..."

# Fonction de création simplifiée
create() {
    USER=$1
    EMAIL=$2
    FIRST=$3
    LAST=$4
    ROLE=$5

    curl -s -X POST "$KEYCLOAK_URL/admin/realms/$REALM_NAME/users" \
      -H "Authorization: Bearer $TOKEN" \
      -H "Content-Type: application/json" \
      -d '{"username":"'$USER'","email":"'$EMAIL'","firstName":"'$FIRST'","lastName":"'$LAST'","enabled":true,"emailVerified":true,"credentials":[{"type":"password","value":"'$TEST_PASSWORD'","temporary":false}]}'

    sleep 1
    UID=$(curl -s "$KEYCLOAK_URL/admin/realms/$REALM_NAME/users?username=$USER" \
      -H "Authorization: Bearer $TOKEN" | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)

    ROLEDATA=$(curl -s "$KEYCLOAK_URL/admin/realms/$REALM_NAME/roles/$ROLE" -H "Authorization: Bearer $TOKEN")

    curl -s -X POST "$KEYCLOAK_URL/admin/realms/$REALM_NAME/users/$UID/role-mappings/realm" \
      -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d "[$ROLEDATA]"

    echo "  ✅ $USER créé"
}

create "tresorier.mukefi" "tresorier.mukefi@unionflow.test" "Tresorier" "MUKEFI" "TRESORIER"
create "secretaire.mukefi" "secretaire.mukefi@unionflow.test" "Secretaire" "MUKEFI" "SECRETAIRE"
create "credit.mukefi" "credit.mukefi@unionflow.test" "Credit" "MUKEFI" "RESPONSABLE_CREDIT"
create "secretaire.meska" "secretaire.meska@unionflow.test" "Secretaire" "MESKA" "SECRETAIRE"
create "evenements.meska" "evenements.meska@unionflow.test" "Evenements" "MESKA" "RESPONSABLE_EVENEMENTS"

echo "✅ Utilisateurs manquants créés"
