#!/usr/bin/env bash
# Resolve an M365 domain (or UPN) to a tenant GUID via OpenID discovery.
# Usage: resolve-tenant.sh <domain-or-upn-or-tenantid>
# Output (stdout): tenant GUID. Exit 0 on success, 1 on failure.
set -euo pipefail

__ROOT="${CLAUDETOOLS_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)}"

INPUT="${1:?usage: resolve-tenant.sh <domain|upn|tenant-id>}"

# If it looks like a GUID already, pass through.
if [[ "$INPUT" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then
  echo "$INPUT"
  exit 0
fi

# If it's a UPN, strip to domain.
DOMAIN="${INPUT#*@}"

# Lightweight cache keyed by domain.
CACHE_DIR="/tmp/remediation-tool/_tenant-cache"
mkdir -p "$CACHE_DIR"
CACHE_FILE="$CACHE_DIR/${DOMAIN}.txt"
if [[ -f "$CACHE_FILE" ]] && [[ $(find "$CACHE_FILE" -mmin -1440 2>/dev/null) ]]; then
  cat "$CACHE_FILE"
  exit 0
fi

# OpenID discovery — parse issuer URL for tenant GUID.
RESP=$(curl -s --max-time 10 "https://login.microsoftonline.com/${DOMAIN}/v2.0/.well-known/openid-configuration")
TENANT_ID=$(echo "$RESP" | jq -r '.issuer // empty' | sed -E 's|^https://login\.microsoftonline\.com/||;s|/v2\.0/?$||' || true)

if [[ -z "$TENANT_ID" ]] || [[ ! "$TENANT_ID" =~ ^[0-9a-fA-F]{8}- ]]; then
  echo "ERROR: could not resolve tenant for domain: $DOMAIN" >&2
  echo "Response: $RESP" >&2
  bash "$__ROOT/.claude/scripts/log-skill-error.sh" "remediation-tool" "resolve-tenant: OpenID discovery did not return a tenant GUID" --context "domain=$DOMAIN" >/dev/null 2>&1 || true
  exit 1
fi

echo "$TENANT_ID" | tee "$CACHE_FILE"
