#!/usr/bin/env bash
# API flow
# Fill in clientId and clientSecret below before running.

set -euo pipefail

# Config (fill in credentials)
authServerUrl="https://auth.stage.myver.tech"
apiServerUrl="https://api.stage.myver.tech"
clientId="" # fill in your client id
clientSecret="" # fill in your client secret

if [[ -z "$clientId" || -z "$clientSecret" ]]; then
  echo "Set clientId and clientSecret in the script." >&2
  exit 1
fi

SCOPE="brand:read store:read store:write source:read source:write receipt:write payment:write"
AUDIENCE="api.stage.myver.tech"

# -----------------------------
# 1) Token exchange
# -----------------------------
echo "1) Token exchange..."
TOKEN_RESP=$(curl -s -X POST "${authServerUrl}/oauth2/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=${clientId}" \
  -d "client_secret=${clientSecret}" \
  -d "scope=${SCOPE}" \
  -d "audience=${AUDIENCE}")
ACCESS_TOKEN=$(echo "$TOKEN_RESP" | jq -r '.access_token')
if [[ -z "$ACCESS_TOKEN" || "$ACCESS_TOKEN" == "null" ]]; then
  echo "Failed to get access token" >&2
  echo "$TOKEN_RESP" | jq . 2>/dev/null || echo "$TOKEN_RESP" >&2
  exit 1
fi

# -----------------------------
# 2) List brands
# -----------------------------
echo "2) List brands..."
BRANDS_RESP=$(curl -s -X GET "${apiServerUrl}/v1/brands" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}")
ITEMS=$(echo "$BRANDS_RESP" | jq -r '.items')
if [[ -z "$ITEMS" || "$ITEMS" == "null" ]]; then
  echo "No brands or invalid response" >&2
  echo "$BRANDS_RESP" | jq . 2>/dev/null || echo "$BRANDS_RESP" >&2
  exit 1
fi
BRAND_ID=$(echo "$BRANDS_RESP" | jq -r '.items[0].brandId')
if [[ -z "$BRAND_ID" || "$BRAND_ID" == "null" ]]; then
  echo "No brandId in response" >&2
  echo "$BRANDS_RESP" | jq . 2>/dev/null || echo "$BRANDS_RESP" >&2
  exit 1
fi

# -----------------------------
# 3) Create store
# -----------------------------
echo "3) Create store..."
STORE_JSON=$(jq -n \
  --arg brandId "$BRAND_ID" \
  '{
    brandId: $brandId,
    name: "ACME Quality Apparel",
    address: "42 Market Street, Dublin D02 XF85",
    countryCode: "IE",
    defaultCurrency: "EUR",
    vatId: "IE8453927K",
    merchantStoreId: "store-001",
    email: "test@myver.io",
    phoneNumber: "+35312345678",
    website: "www.myver.io",
    integrationStoreId: "integration-store-001"
  }')
STORE_RESP=$(curl -s -X POST "${apiServerUrl}/v1/stores" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d "$STORE_JSON")
STORE_ID=$(echo "$STORE_RESP" | jq -r '.storeId')
if [[ -z "$STORE_ID" || "$STORE_ID" == "null" ]]; then
  echo "Failed to create store" >&2
  echo "$STORE_RESP" | jq . 2>/dev/null || echo "$STORE_RESP" >&2
  exit 1
fi

# -----------------------------
# 4) Create source
# -----------------------------
echo "4) Create source..."
SOURCE_JSON='{"type":"receipts","description":"CashWave Technologies Point of Sale"}'
SOURCE_RESP=$(curl -s -X POST "${apiServerUrl}/v1/sources" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d "$SOURCE_JSON")
SOURCE_ID=$(echo "$SOURCE_RESP" | jq -r '.sourceId')
if [[ -z "$SOURCE_ID" || "$SOURCE_ID" == "null" ]]; then
  echo "Failed to create source" >&2
  echo "$SOURCE_RESP" | jq . 2>/dev/null || echo "$SOURCE_RESP" >&2
  exit 1
fi

# -----------------------------
# 5) Send receipt
# -----------------------------
echo "5) Send receipt..."
RECEIPT_ID="rcpt-$(uuidgen 2>/dev/null || echo "$(date +%s)-$$-$(od -An -N4 -tx1 /dev/urandom 2>/dev/null | tr -d ' ')")"
RECEIPT_JSON=$(jq -n \
  --arg storeId "$STORE_ID" \
  --arg receiptId "$RECEIPT_ID" \
  '{
    header: {
      storeId: $storeId,
      created: "2025-08-25T08:57:37+00:00",
      receiptId: $receiptId
    },
    lineItems: [
      {
        quantity: { value: 2, unit: "each" },
        description: "Premium Cotton T-Shirt",
        modifiers: [
          {
            type: "discount",
            amount: { net: -9.99, currency: "EUR" }
          }
        ],
        item: {
          unitPrice: { net: 29.99, currency: "EUR" }
        },
        lineAmount: { net: 49.99, currency: "EUR" }
      }
    ],
    totals: [
      { type: "subtotal", sum: { amount: 49.99, currency: "EUR" } },
      { type: "vat", sum: { amount: 11.50, currency: "EUR" } },
      { type: "amountDue", sum: { amount: 61.49, currency: "EUR" } }
    ],
    payments: [
      {
        paymentType: "card",
        paid: { amount: 61.49, currency: "EUR" },
        paymentTypeLabel: "VISA",
        lastFour: "4242",
        approvalCode: "048236"
      }
    ]
  }')
RECEIPT_RESP=$(curl -s -w "\n%{http_code}" -X POST "${apiServerUrl}/v1/sources/${SOURCE_ID}/receipts" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d "$RECEIPT_JSON")
RECEIPT_HTTP_CODE=$(echo "$RECEIPT_RESP" | tail -n1)
RECEIPT_BODY=$(echo "$RECEIPT_RESP" | sed '$d')
if [[ "$RECEIPT_HTTP_CODE" != "204" ]]; then
  echo "Receipt POST failed (HTTP $RECEIPT_HTTP_CODE)" >&2
  echo "$RECEIPT_BODY" | jq . 2>/dev/null || echo "$RECEIPT_BODY" >&2
  exit 1
fi

# -----------------------------
# Teardown
# -----------------------------
echo "Teardown: delete source and store..."
DELETE_SOURCE_RESP=$(curl -s -w "\n%{http_code}" -X DELETE "${apiServerUrl}/v1/sources/${SOURCE_ID}" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}")
DELETE_SOURCE_CODE=$(echo "$DELETE_SOURCE_RESP" | tail -n1)
if [[ "$DELETE_SOURCE_CODE" != "204" && "$DELETE_SOURCE_CODE" != "200" ]]; then
  echo "Delete source failed (HTTP $DELETE_SOURCE_CODE)" >&2
  echo "$DELETE_SOURCE_RESP" | sed '$d' | jq . 2>/dev/null || echo "$DELETE_SOURCE_RESP" >&2
fi
DELETE_STORE_RESP=$(curl -s -w "\n%{http_code}" -X DELETE "${apiServerUrl}/v1/stores/${STORE_ID}" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}")
DELETE_STORE_CODE=$(echo "$DELETE_STORE_RESP" | tail -n1)
if [[ "$DELETE_STORE_CODE" != "204" && "$DELETE_STORE_CODE" != "200" ]]; then
  echo "Delete store failed (HTTP $DELETE_STORE_CODE)" >&2
  echo "$DELETE_STORE_RESP" | sed '$d' | jq . 2>/dev/null || echo "$DELETE_STORE_RESP" >&2
fi

echo "Done."
