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 enquirySchema = z.object({
  customerId: z.string().min(1, 'Please select a customer'),
  contactId: z.string().optional().nullable(),
  title: z.string().min(2, 'Title must be at least 2 characters'),
  description: z.string().optional(),
  requirement: z.string().optional(),
  projectName: z.string().optional(),
  projectLocation: z.string().optional(),
  branchId: z.string().optional().nullable(),
  productType: z.string().min(1, 'Please select a product type'),
  status: z.string().min(1, 'Please select a status'),
  priority: z.string().min(1, 'Please select a priority'),
  leadChannel: z.string().optional().nullable(),
  estimatedValue: coerceOptionalNumber('Estimated value must be a number').refine(
    (value) => value === undefined || value >= 0,
    'Estimated value must be 0 or greater'
  ),
  chancePercent: coerceOptionalNumber('Chance percent must be a number').refine(
    (value) => value === undefined || (value >= 0 && value <= 100),
    'Chance percent must be between 0 and 100'
  ),
  expectedCloseDate: z.string().optional().nullable(),
  competitor: z.string().optional(),
  source: z.string().optional(),
  isHotProject: z.boolean().default(false),
  notes: z.string().optional(),
  isActive: z.boolean().default(true),
  projectParties: z
    .array(
      z.object({
        customerId: z.string().min(1, 'Please select a customer'),
        role: z.string().min(1, 'Please select a role'),
        remark: z.string().nullable().optional()
      })
    )
    .optional()
});

export const enquiryFollowupSchema = z.object({
  followupDate: z.string().min(1, 'Follow-up date is required'),
  followupType: z.string().min(1, 'Please select a follow-up type'),
  contactId: z.string().optional().nullable(),
  outcome: z.string().optional(),
  notes: z.string().optional(),
  nextFollowupDate: z.string().optional().nullable(),
  nextAction: z.string().optional()
});

export type EnquiryFormValues = z.input<typeof enquirySchema>;
export type EnquiryFollowupFormValues = z.input<typeof enquiryFollowupSchema>;
