apiVersion: v1
kind: ConfigMap
metadata:
  name: keycloak-client-config
  namespace: keycloak
data:
  # Client configuration script for Keycloak
  configure-clients.sh: |
    #!/bin/bash
    # Configure Keycloak clients via REST API
    # This should be run after Keycloak is deployed
    
    KEYCLOAK_URL="${KEYCLOAK_URL:-http://localhost:8080}"
    ADMIN_USER="${KEYCLOAK_ADMIN:-admin}"
    ADMIN_PASSWORD="${KEYCLOAK_ADMIN_PASSWORD:-admin}"
    REALM="${REALM:-master}"
    
    # Get admin token
    TOKEN=$(curl -s -X POST "${KEYCLOAK_URL}/realms/${REALM}/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" | jq -r '.access_token')
    
    if [ "$TOKEN" == "null" ] || [ -z "$TOKEN" ]; then
      echo "Failed to get admin token"
      exit 1
    fi
    
    # Create sankofa-api client (confidential)
    curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${REALM}/clients" \
      -H "Authorization: Bearer ${TOKEN}" \
      -H "Content-Type: application/json" \
      -d '{
        "clientId": "sankofa-api",
        "name": "Sankofa API Client",
        "description": "GraphQL API backend client",
        "enabled": true,
        "clientAuthenticatorType": "client-secret",
        "secret": "'${SANKOFA_API_CLIENT_SECRET:-generate-me}'",
        "standardFlowEnabled": false,
        "implicitFlowEnabled": false,
        "directAccessGrantsEnabled": true,
        "serviceAccountsEnabled": true,
        "publicClient": false,
        "protocol": "openid-connect",
        "attributes": {
          "access.token.lifespan": "300",
          "client.secret.creation.time": "'$(date +%s)'"
        }
      }'
    
    # Create portal-client (confidential)
    curl -s -X POST "${KEYCLOAK_URL}/admin/realms/${REALM}/clients" \
      -H "Authorization: Bearer ${TOKEN}" \
      -H "Content-Type: application/json" \
      -d '{
        "clientId": "portal-client",
        "name": "Sankofa Portal Client",
        "description": "Portal frontend client",
        "enabled": true,
        "clientAuthenticatorType": "client-secret",
        "secret": "'${PORTAL_CLIENT_SECRET:-generate-me}'",
        "standardFlowEnabled": true,
        "implicitFlowEnabled": false,
        "directAccessGrantsEnabled": true,
        "serviceAccountsEnabled": false,
        "publicClient": false,
        "protocol": "openid-connect",
        "redirectUris": [
          "http://localhost:3000/*",
          "https://portal.sankofa.nexus/*",
          "https://*.sankofa.nexus/*"
        ],
        "webOrigins": [
          "http://localhost:3000",
          "https://portal.sankofa.nexus",
          "https://*.sankofa.nexus"
        ],
        "attributes": {
          "access.token.lifespan": "1800"
        }
      }'
    
    echo "Keycloak clients configured successfully"

