import * as z from 'zod';

function coerceOptionalNumber(message: string) {
  return z.preprocess((value) => {
    if (value === '' || value === null || value === undefined) {
      return undefined;
    }

    if (typeof value === 'number') {
      return value;
    }

    if (typeof value === 'string') {
      const trimmed = value.trim();
      if (!trimmed) {
        return undefined;
      }

      return Number(trimmed);
    }

    return value;
  }, z.number().refine((value) => !Number.isNaN(value), message).optional());
}

export const opportunityMarkWonSchema = z.object({
  poNumber: z.string().min(1, 'PO number required'),
  poDate: z.string().min(1, 'PO date required'),
  poAmount: coerceOptionalNumber('PO amount must be number').refine(
    (value) => value === undefined || value >= 0,
    'PO amount must be 0 or greater'
  ),
  poCurrency: z.string().optional().nullable(),
  remark: z.string().optional().nullable()
});

export const opportunityMarkLostSchema = z.object({
  lostReason: z.string().min(1, 'Lost reason required'),
  lostDetail: z.string().optional().nullable(),
  lostCompetitor: z.string().optional().nullable(),
  lostRemark: z.string().optional().nullable()
});

export const opportunityMarkCancelledSchema = z.object({
  cancelReason: z.string().min(1, 'Cancel reason required')
});

export const opportunityMarkNoQuotationSchema = z.object({
  noQuotationReason: z.string().min(1, 'No quotation reason required')
});

export const opportunityReopenSchema = z.object({
  reopenReason: z.string().min(3, 'Reopen reason required')
});

export type OpportunityMarkWonFormValues = z.input<typeof opportunityMarkWonSchema>;
export type OpportunityMarkLostFormValues = z.input<typeof opportunityMarkLostSchema>;
export type OpportunityMarkCancelledFormValues = z.input<typeof opportunityMarkCancelledSchema>;
export type OpportunityMarkNoQuotationFormValues = z.input<typeof opportunityMarkNoQuotationSchema>;
export type OpportunityReopenFormValues = z.input<typeof opportunityReopenSchema>;
