import { z } from 'zod';
import type { OutboxHandler } from '../types.js';
import { processSupportRefundRetry } from './support.refund.retry.js';

const payloadSchema = z.looseObject({
  caseId: z.string(),
  purchaseId: z.string(),
  amountCents: z.number().positive(),
  outcome: z.enum(['refund_full', 'refund_partial']),
  executedBy: z.enum(['vendor_auto', 'customer_accept', 'ai_auto', 'human']),
  email: z
    .object({
      templateKey: z.enum(['support.case_resolved', 'support.customer_decided']),
      recipients: z.array(z.enum(['customer', 'vendor'])),
      params: z.record(z.string(), z.string()),
    })
    .nullable()
    .optional(),
});

type Payload = z.infer<typeof payloadSchema>;

export const supportCaseRefundRequested: OutboxHandler<Payload> = {
  type: 'support-case.refund.requested',
  payloadSchema,
  async handle(ctx, payload, event) {
    await processSupportRefundRetry(ctx, { ...payload, attempt: 1 }, event);
  },
};
