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

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

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

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

    // ── Relations ──
    customer: relationFieldSchema,
    department: relationFieldSchema,

    // ── Optional fields ──
    date: z.string().min(1, "Date is required").date("Enter a valid date"),
    status: z.enum(CreditNoteStatus).optional(),
    notes: z.string().optional(),
    credit_invoice: optionalStringMax255Schema,
})

type CreditNoteFormValues = z.infer<typeof creditNoteFormSchema>

export { creditNoteFormSchema, relationFieldSchema }
export type { CreditNoteFormValues }
