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

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 optionalNumberSchema = z.preprocess(
    (value) => (value === "" || value == null ? undefined : value),
    z.coerce.number().min(0).optional(),
)

const purchaseOrderItemSchema = z.object({
    part_id: z.number(),
    title: z.string(),
    quantity: z.number().min(1, "Quantity must be at least 1"),
    rate: z.number().min(0, "Rate must be non-negative"),
    description: z.string().optional(),
})

const purchaseOrderFormSchema = z.object({
    // ── Relations ──
    vendor: requiredRelationFieldSchema,
    job_card: requiredRelationFieldSchema,
    department: requiredRelationFieldSchema,

    // ── Basic info ──
    title: optionalStringMax255Schema,
    order_date: optionalDateSchema,
    delivery_date: optionalDateSchema,
    notes: z.string().optional(),
    terms_and_conditions: z.string().optional(),
    discount_type: z.enum(InvoiceDiscount).optional(),
    discount_amount: optionalNumberSchema,
    label_ids: z.array(z.number()).optional(),
    order_number: z.string().trim().min(1, "Order number is required").max(255, "Order number must be at most 255 characters"),

    // ── Items (parts) ──
    items: z.array(purchaseOrderItemSchema).optional(),
})

type PurchaseOrderFormValues = z.infer<typeof purchaseOrderFormSchema>
type PurchaseOrderItem = z.infer<typeof purchaseOrderItemSchema>

export { purchaseOrderFormSchema, purchaseOrderItemSchema, relationFieldSchema }
export type { PurchaseOrderFormValues, PurchaseOrderItem }
 
