// apps/web/src/server/domain/fulfillment/mode.ts
export type FulfillmentMode = 'delivery' | 'pickup' | 'voucher' | 'none';

export interface FulfillmentInfo {
  mode: FulfillmentMode;
  pickupAddress?: string | null;
  pickupStart?: string | null;
  pickupEnd?: string | null;
  specialInstructions?: string | null;
  validFrom?: string | null;
  validUntil?: string | null;
}

export interface FulfillmentInput {
  dealType: 'COUPON' | 'GROUP' | 'ITEM';
  isVoucher: boolean;
  pickupEnabled: boolean;
  pickupAddress: string | null;
  pickupStart: string | null;
  pickupEnd: string | null;
  specialInstructions: string | null;
  windowStart: Date | null;
  windowEnd: Date | null;
}

export function resolveFulfillment(input: FulfillmentInput): FulfillmentInfo {
  // 1. Pickup is an explicit vendor opt-in (ITEM only) and overrides everything.
  if (input.pickupEnabled) {
    return {
      mode: 'pickup',
      pickupAddress: input.pickupAddress,
      pickupStart: input.pickupStart,
      pickupEnd: input.pickupEnd,
      specialInstructions: input.specialInstructions,
    };
  }
  // 2. ITEM (non-pickup) ships — mirrors createShipmentsOnPaid's dealType='ITEM' filter exactly.
  if (input.dealType === 'ITEM') {
    return { mode: 'delivery' };
  }
  // 3. COUPON / GROUP / explicit voucher → redeemed at venue, never shipped.
  if (input.dealType === 'COUPON' || input.dealType === 'GROUP' || input.isVoucher) {
    return {
      mode: 'voucher',
      specialInstructions: input.specialInstructions,
      validFrom: input.windowStart ? input.windowStart.toISOString() : null,
      validUntil: input.windowEnd ? input.windowEnd.toISOString() : null,
    };
  }
  // 4. Unreachable for known dealTypes.
  return { mode: 'none' };
}
