import { z } from "zod"

const relationFieldSchema = z
    .object({ value: z.string(), label: z.string() })
    .nullable()

const requiredRelationFieldSchema = relationFieldSchema.superRefine((value, ctx) => {
    if (!value?.value) {
        ctx.addIssue({
            code: z.ZodIssueCode.custom,
            message: "This field is required",
        })
    }
})

const optionalDateSchema = z.preprocess(
    (value) => (value === "" || value == null ? undefined : value),
    z.string().date().optional(),
)

const optionalStringMax255Schema = z.preprocess(
    (value) => (value === "" || value == null ? undefined : value),
    z.string().max(255, "Must be at most 255 characters").optional(),
)

const paymentReceivedFormSchema = z.object({
    // ── Relations ──
    job_card: relationFieldSchema,
    invoice: relationFieldSchema,
    payment_mode: requiredRelationFieldSchema,
    customer: requiredRelationFieldSchema,

    // ── Payment info ──
    amount_received: z.coerce.number().min(0, "Amount received must be 0 or more"),
    payment_number: optionalStringMax255Schema,
    payment_date: optionalDateSchema,
    reference_date: optionalDateSchema,
    deposit_to: optionalStringMax255Schema,
    note: optionalStringMax255Schema,
})

type PaymentReceivedFormValues = z.infer<typeof paymentReceivedFormSchema>

export { paymentReceivedFormSchema, relationFieldSchema }
export type { PaymentReceivedFormValues }
