/**
 * Zod schemas for personal deal API routes.
 */

import { z } from 'zod';
import { createDealBodyShape } from './vendor.js';

// ─── Accept personal deal request ────────────────────────────────────────────

/**
 * Input schema for the new deal created via personal deal accept.
 *
 * imageSet is intentionally excluded: personal deals clone the source deal's
 * approved images before transitioning from DRAFT to ACTIVE.
 *
 * delivery is restricted to literal 'DELIVERY' (FDS §6.6) — personal deals do
 * not support pickup. isVoucher is restricted to literal false — personal deals
 * are physical/standard deals only.
 */
export const acceptPersonalDealNewDealInputSchema = createDealBodyShape
  .omit({ imageSet: true, isVoucher: true })
  .extend({
    delivery: z.literal('DELIVERY'),
    isVoucher: z.literal(false),
  })
  .superRefine((val, ctx) => {
    const discounted =
      Math.round(Number(val.originalPrice) * (1 - val.discountPercent / 100) * 100) / 100;
    if (discounted < 3) {
      ctx.addIssue({
        code: 'custom',
        message: 'Deal price after discount must be at least ₪3',
        path: ['discountPercent'],
      });
    }
    if (val.windowStart) {
      const skewMs = 5 * 60 * 1000;
      if (new Date(val.windowStart).getTime() < Date.now() - skewMs) {
        ctx.addIssue({
          path: ['windowStart'],
          code: 'custom',
          message: 'windowStart must not be in the past',
        });
      }
    }
  });

export type AcceptPersonalDealNewDealInput = z.infer<typeof acceptPersonalDealNewDealInputSchema>;

export const acceptPersonalDealBodySchema = z.object({
  newDealInput: acceptPersonalDealNewDealInputSchema,
});

export type AcceptPersonalDealBody = z.infer<typeof acceptPersonalDealBodySchema>;

// ─── Request personal deal (customer-side) ────────────────────────────────────

export const requestPersonalDealBodySchema = z.object({
  sourceDealId: z.uuid(),
});

export type RequestPersonalDealBody = z.infer<typeof requestPersonalDealBodySchema>;
