import { z } from 'zod';

export function assertSingleOrderLine(lineCount: number): void {
  if (lineCount !== 1) {
    throw new Error('Factory purchase cleanup requires exactly one order line');
  }
}

export const purchaseInputSchema = z
  .object({
    key: z.uuid(),
    orderId: z.uuid(),
    buyerUserId: z.uuid(),
    dealId: z.uuid(),
    dealType: z.enum(['COUPON', 'ITEM']).optional(),
    quantity: z.number().int().positive().max(10).default(1),
    deliveredAtDaysAgo: z.number().int().min(0).max(365).nullable().optional(),
    redemptionState: z.enum(['UNREDEEMED', 'REDEEMED']).optional(),
    settlementState: z.enum(['HELD', 'RELEASED']).default('HELD'),
    qrTokenHash: z
      .string()
      .regex(/^[0-9a-f]{64}$/)
      .optional(),
  })
  .superRefine((input, context) => {
    if (input.dealType === 'COUPON' && input.deliveredAtDaysAgo !== undefined) {
      context.addIssue({
        code: 'custom',
        path: ['deliveredAtDaysAgo'],
        message: 'Coupons cannot be delivered',
      });
    }
    if (input.dealType === 'ITEM' && input.redemptionState !== undefined) {
      context.addIssue({
        code: 'custom',
        path: ['redemptionState'],
        message: 'Items cannot be redeemed',
      });
    }
  });

export type PurchaseFactoryInput = z.infer<typeof purchaseInputSchema>;
