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

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

const APPOINTMENT_STATUS_OPTIONS = AppointmentStatus.map((v) => ({
    value: v,
    label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
}))

const appointmentFormSchema = z
    .object({
        title: z.string().min(1, "Title is required").max(255, "Title cannot exceed 255 characters"),
        date: z.string().min(1, "Date is required"),
        from_time: z.string().min(1, "Start time is required"),
        to_time: z.string().min(1, "End time is required"),
        customer: relationFieldSchema,
        vehicle: relationFieldSchema,
        service_writer: relationFieldSchema.refine((val) => !!val?.value, "Service writer is required"),
        technician: relationFieldSchema,
        department: relationFieldSchema,
        job_card: relationFieldSchema,
        notes: z.string().optional(),
        status: z.string().optional(),
    })
    .superRefine((val, ctx) => {
        if (val.from_time && val.to_time && val.to_time <= val.from_time) {
            ctx.addIssue({
                code: z.ZodIssueCode.custom,
                path: ["to_time"],
                message: "End time must be after start time",
            })
        }
    })

type AppointmentFormValues = z.infer<typeof appointmentFormSchema>

export { appointmentFormSchema, relationFieldSchema, APPOINTMENT_STATUS_OPTIONS }
export type { AppointmentFormValues }
