#!/usr/bin/env bash
# Nexus365Desk Public API — curl examples.
# Replace the four placeholders below with values from the setup wizard.

set -euo pipefail

TENANT_ID="${TENANT_ID:-your-tenant-id-guid}"
CLIENT_ID="${CLIENT_ID:-your-client-id-guid}"
CLIENT_SECRET="${CLIENT_SECRET:-your-client-secret}"
SITE_ID="${SITE_ID:-contoso.sharepoint.com,site-collection-guid,site-guid}"

GRAPH="https://graph.microsoft.com/v1.0/sites/${SITE_ID}"

# ── 1. Get a token ───────────────────────────────────────────────────
TOKEN=$(curl -sS -X POST \
  "https://login.microsoftonline.com/${TENANT_ID}/oauth2/v2.0/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=${CLIENT_ID}" \
  -d "client_secret=${CLIENT_SECRET}" \
  -d "scope=https://graph.microsoft.com/.default" \
  | jq -r .access_token)

echo "Token acquired (${#TOKEN} chars)"

# ── 2. List the 10 newest open tickets ──────────────────────────────
curl -sS \
  --get "${GRAPH}/lists/SD_Tickets/items" \
  --data-urlencode '$expand=fields' \
  --data-urlencode '$filter=fields/SD_Status eq '\''New'\''' \
  --data-urlencode '$orderby=fields/Created desc' \
  --data-urlencode '$top=10' \
  -H "Authorization: Bearer ${TOKEN}" \
  | jq '.value[] | {id, title: .fields.Title, priority: .fields.SD_Priority, created: .fields.Created}'

# ── 3. Create a new ticket ──────────────────────────────────────────
NEW_TICKET=$(curl -sS -X POST "${GRAPH}/lists/SD_Tickets/items" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "fields": {
      "Title": "Printer offline on floor 3",
      "SD_Description": "HP M553 not responding to ping since 09:00.",
      "SD_Priority": "Medium",
      "SD_Status": "New",
      "SD_Category": "Hardware",
      "SD_SubmittedBy": "user@contoso.com",
      "SD_SubmittedByName": "Facilities",
      "SD_SubmittedByEmail": "user@contoso.com"
    }
  }')
TICKET_ID=$(echo "${NEW_TICKET}" | jq -r .id)
echo "Created ticket ${TICKET_ID}"

# ── 4. Add a comment ────────────────────────────────────────────────
curl -sS -X POST "${GRAPH}/lists/SD_Comments/items" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{
    \"fields\": {
      \"Title\": \"Triage\",
      \"SD_TicketId\": ${TICKET_ID},
      \"SD_Body\": \"Dispatched field engineer.\",
      \"SD_AuthorEmail\": \"agent@contoso.com\",
      \"SD_AuthorName\": \"Agent Smith\",
      \"SD_IsInternal\": false
    }
  }" | jq '.id'

# ── 5. Resolve the ticket ───────────────────────────────────────────
curl -sS -X PATCH "${GRAPH}/lists/SD_Tickets/items/${TICKET_ID}/fields" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -H "If-Match: *" \
  -d '{ "SD_Status": "Resolved", "SD_AssignedTo": "agent@contoso.com" }' \
  | jq '{id: .id, status: .SD_Status}'

echo "Done."
