import { z } from "zod"

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

const partLineSchema = z.object({
    part: relationFieldSchema,
    quantity: z.coerce.number().int().min(1, "Quantity must be at least 1"),
    operation: z.enum(["add", "subtract"]).default("add"),
    rate: z.coerce.number().min(0, "Rate must be 0 or more"),
})

export const inventoryAdjustmentFormSchema = z.object({
    reference_number: z.string().min(1, "Reference number is required").max(255, "Reference number cannot exceed 255 characters"),
    date: z.string().min(1, "Date is required"),
    // TODO: pending chart-of-accounts module. Until then this is a free integer
    // that the backend stores as-is; replace with an async select bound to the
    // chart-of-accounts API once the module ships.
    chart_of_account: z.preprocess(
        (v) => (v === "" || v == null ? undefined : v),
        z.coerce.number().int("Chart of account must be a whole number").optional(),
    ),
    reason: relationFieldSchema,
    notes: z.string().optional(),
    parts: z.array(partLineSchema).min(1, "At least one part is required"),
})

export type InventoryAdjustmentFormValues = z.infer<typeof inventoryAdjustmentFormSchema>
export type PartLineValues = z.infer<typeof partLineSchema>
