#!/usr/bin/env sh
set -eu

# Run only after operator approval. Replace the .example addresses below with
# your approved sender and intended recipient. Keep the key on your server.
# Sending is disabled at this docs release; production activation is separate.
# Save MAILCORE_IDEMPOTENCY_KEY with this order/event before the first attempt;
# reuse it and the unchanged payload after an uncertain HTTP response.
# This example performs one attempt. A queued/accepted result is not delivery;
# never blindly send an ambiguous message again under a new key.
: "${MAILCORE_API_KEY:?Set the operator-issued server key}"
: "${MAILCORE_IDEMPOTENCY_KEY:?Set the key persisted with this application event}"
case "$MAILCORE_IDEMPOTENCY_KEY" in
  *[!A-Za-z0-9._:-]*) printf '%s\n' 'Invalid idempotency key characters' >&2; exit 1 ;;
esac
if [ "${#MAILCORE_IDEMPOTENCY_KEY}" -lt 16 ] || [ "${#MAILCORE_IDEMPOTENCY_KEY}" -gt 128 ]; then
  printf '%s\n' 'Idempotency key must contain 16–128 characters' >&2
  exit 1
fi

curl --silent --show-error --fail-with-body \
  --connect-timeout 10 --max-time 30 \
  https://mailcore.uz/api/email/v1/emails \
  -H "Authorization: Bearer ${MAILCORE_API_KEY}" \
  -H "Idempotency-Key: ${MAILCORE_IDEMPOTENCY_KEY}" \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "from": "Example Shop <orders@notify.example>",
    "to": "customer@recipient.example",
    "subject": "Order #8421 completed",
    "text": "Your order has been completed.",
    "tags": {"order_id": "8421"}
  }'
