import { z } from "zod"
import { DiscountType } from "@garage/api"

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

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

const optionalNumberSchema = z.preprocess(
    (value) => (value === "" || value == null ? undefined : value),
    z.coerce.number().min(0).optional(),
)

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

const estimateFormSchema = z.object({
    // ── Required fields ──
    title: z.string().trim().min(1, "Title is required").max(255, "Title must be at most 255 characters"),

    // ── Relations ──
    customer: requiredRelationFieldSchema,
    vehicle: requiredRelationFieldSchema,
    department: requiredRelationFieldSchema,
    insurance_type: relationFieldSchema,
    insurer: relationFieldSchema,
    service_writer: relationFieldSchema,

    // ── Optional fields ──
    estimate_number: z.string().trim().min(1, "Estimate number is required").max(255, "Estimate number must be at most 255 characters"),
    date: optionalDateSchema,
    has_insurance: z.boolean().optional(),
    enable_digital_authorisation: z.boolean().optional(),
    footer: z.string().optional(),
    discount: z.enum(DiscountType).optional(),
    discount_amount: optionalNumberSchema,

    // ── Remarks (array of strings) ──
    remarks: z.array(z.string()).optional(),

    // ── Labels ──
    labels: z
        .array(
            z.object({
                id: z.number(),
                title: z.string(),
                color_code: z.string(),
            }),
        )
        .optional(),
})

type EstimateFormValues = z.infer<typeof estimateFormSchema>

export { estimateFormSchema, relationFieldSchema }
export type { EstimateFormValues }
