#!/bin/bash

set -e

DIRECTUS_URL="${DIRECTUS_URL:-http://localhost:8055}"
ADMIN_EMAIL="${ADMIN_EMAIL:-admin@deusens.com}"
ADMIN_PASSWORD="${ADMIN_PASSWORD:-Admin1234!}"
ROLE_ID="${ROLE_ID:-}"
ROLE_NAME="${ROLE_NAME:-}"

TOKEN=$(curl -sf -X POST "$DIRECTUS_URL/auth/login" \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"$ADMIN_EMAIL\",\"password\":\"$ADMIN_PASSWORD\"}" \
  | grep -o '"access_token":"[^"]*"' | head -1 | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
  echo "Authentication failed"
  exit 1
fi

if [ -z "$ROLE_ID" ] && [ -n "$ROLE_NAME" ]; then
  ROLE_ID=$(curl -sf "$DIRECTUS_URL/roles?fields=id,name" \
    -H "Authorization: Bearer $TOKEN" \
    | python -c "import sys, json; data=json.load(sys.stdin).get('data', []); name='$ROLE_NAME'.lower(); print(next((str(item['id']) for item in data if str(item.get('name','')).lower()==name), ''))")
fi

if [ -z "$ROLE_ID" ]; then
  echo "ROLE_ID or ROLE_NAME is required."
  echo "Available roles:"
  curl -sf "$DIRECTUS_URL/roles?fields=id,name" -H "Authorization: Bearer $TOKEN"
  exit 1
fi

upsert_permission() {
  local ACTION="$1"
  local EXISTING_ID
  EXISTING_ID=$(curl -sf "$DIRECTUS_URL/permissions?filter[role][_eq]=$ROLE_ID&filter[collection][_eq]=events_page_content&filter[action][_eq]=$ACTION&fields=id" \
    -H "Authorization: Bearer $TOKEN" \
    | python -c "import sys, json; data=json.load(sys.stdin).get('data', []); print(data[0]['id'] if data else '')")

  local PAYLOAD
  PAYLOAD=$(cat <<JSON
{"role":"$ROLE_ID","collection":"events_page_content","action":"$ACTION","permissions":{},"validation":{},"presets":{},"fields":["*"]}
JSON
)

  if [ -n "$EXISTING_ID" ]; then
    curl -sf -X PATCH "$DIRECTUS_URL/permissions/$EXISTING_ID" \
      -H "Authorization: Bearer $TOKEN" \
      -H "Content-Type: application/json" \
      -d "$PAYLOAD" > /dev/null
    echo "Updated $ACTION permission for role $ROLE_ID"
  else
    curl -sf -X POST "$DIRECTUS_URL/permissions" \
      -H "Authorization: Bearer $TOKEN" \
      -H "Content-Type: application/json" \
      -d "$PAYLOAD" > /dev/null
    echo "Created $ACTION permission for role $ROLE_ID"
  fi
}

upsert_permission "read"
upsert_permission "create"
upsert_permission "update"
upsert_permission "delete"

echo "events_page_content permissions granted for role $ROLE_ID"
