/**
 * Zod schemas for refund API routes.
 */

import { z } from 'zod';

// ─── Request cancellation ─────────────────────────────────────────────────────

export const requestCancellationBodySchema = z.object({
  purchaseId: z.uuid(),
  reason: z.string().trim().min(1).max(1000),
});

export type RequestCancellationBody = z.infer<typeof requestCancellationBodySchema>;

const positiveRefundAmount = z
  .string()
  .trim()
  .regex(/^\d+(\.\d{1,2})?$/, 'Amount must be a positive decimal')
  .refine((v) => parseFloat(v) >= 0.01, 'Amount must be at least 0.01 ILS');

// ─── Approve refund ───────────────────────────────────────────────────────────

export const approveRefundBodySchema = z.object({
  /** Optional override amount - defaults to calculated amount if omitted. */
  amount: positiveRefundAmount.optional(),
});

export type ApproveRefundBody = z.infer<typeof approveRefundBodySchema>;

// ─── Execute refund ───────────────────────────────────────────────────────────

export const executeRefundBodySchema = z.object({
  purchaseId: z.uuid(),
  amount: positiveRefundAmount,
});

export type ExecuteRefundBody = z.infer<typeof executeRefundBodySchema>;

// ─── Voucher complaint ────────────────────────────────────────────────────────

export const voucherComplaintBodySchema = z.object({
  purchaseId: z.uuid(),
  reason: z.string().trim().min(1).max(1000),
});

export type VoucherComplaintBody = z.infer<typeof voucherComplaintBodySchema>;

// ─── Response schemas ─────────────────────────────────────────────────────────

export const refundBreakdownSchema = z.object({
  customerRefund: z.number(),
  platformShare: z.number(),
  vendorShare: z.number(),
});

export type RefundBreakdown = z.infer<typeof refundBreakdownSchema>;

export const refundApproveResponseSchema = z.object({
  ok: z.literal(true),
  purchaseId: z.uuid(),
  refundAmount: z.string(),
  breakdown: refundBreakdownSchema,
  message: z.string(),
});

export type RefundApproveResponse = z.infer<typeof refundApproveResponseSchema>;

export const refundExecuteResponseSchema = z.object({
  ok: z.literal(true),
  purchaseId: z.uuid(),
  refundId: z.string(),
  amount: z.string(),
  outboxId: z.string(),
});

export type RefundExecuteResponse = z.infer<typeof refundExecuteResponseSchema>;
