set -euo pipefail
printf '%s\n' none > /tmp/apply-request
: > /tmp/authorization-request
: > /tmp/execution-result
jq -n --arg decision "$APPROVAL" --arg ticket "$CHANGE_TICKET" --arg comment "$REVIEW_COMMENTS" \
  --arg policy "$DECISION" --arg workflow "$WORKFLOW" --arg stack "$STACK" \
  --arg fingerprint "$FINGERPRINT" --arg time "$(date -u +%FT%TZ)" \
  '{decision:$decision,policy:$policy,changeTicket:$ticket,reviewComments:$comment,workflow:$workflow,stack:$stack,planFingerprint:$fingerprint,recordedAt:$time}' > /tmp/approval-audit.json
case "$DECISION" in
  NoChanges) iacstack result --outcome NoChanges; exit 0 ;;
  Deny) iacstack result --outcome Blocked --reason PolicyDenied; exit 0 ;;
  RequireApproval)
    if [[ "$APPROVAL" != Approve ]]; then
      iacstack result --outcome Blocked --reason ApprovalRejected
      exit 0
    fi
    if [[ ${#CHANGE_TICKET} -gt 64 || ${#REVIEW_COMMENTS} -gt 1000 ]]; then
      printf '%s\n' 'Approval blocked: ticket or comment exceeds the allowed length.' >&2
      iacstack result --outcome Blocked --reason InvalidApprovalParameters --message 'Ticket must be at most 64 characters and comment at most 1000.'
      exit 0
    fi
    if [[ "$ENVIRONMENT" == PROD && ! "$CHANGE_TICKET" =~ [^[:space:]] ]]; then
      printf '%s\n' 'Approval blocked: PROD requires a change ticket.' >&2
      iacstack result --outcome Blocked --reason InvalidApprovalParameters --message 'A change ticket is required for PROD approval.'
      exit 0
    fi
    if [[ "$ENVIRONMENT" == PROD && ! "$REVIEW_COMMENTS" =~ [^[:space:]] ]]; then
      printf '%s\n' 'Approval blocked: PROD requires review comments.' >&2
      iacstack result --outcome Blocked --reason InvalidApprovalParameters --message 'Review comments are required for PROD approval.'
      exit 0
    fi ;;
  AutoApply) ;;
  *) exit 1 ;;
esac
if [[ "$EXTERNAL" == true ]]; then
  iacstack result --outcome Blocked --reason ExternalFlowLogReview
  exit 0
fi
iacstack authorization request --token "$TOKEN"
printf '%s\n' "$TOKEN" > /tmp/apply-request
