import { z } from "zod";
import {
  numberInRange,
  nonNegativeNumberFromForm,
  positiveNumberFromForm,
  nullableIntIdFromForm,
  booleanFromForm,
  isoDateString,
} from "./common";

export const IssuedOrderItemSchema = z.object({
  description: z.string().max(500).nullish(),
  item_description: z.string().max(5000).nullish(),
  quantity: positiveNumberFromForm.optional(),
  unit: z.string().max(20).nullish(),
  unit_price: nonNegativeNumberFromForm.optional(),
  vat_rate: numberInRange(0, 100).optional(),
  position: z.number().int().nonnegative().optional(),
});

const ISSUED_ORDER_STATUSES = [
  "draft",
  "sent",
  "confirmed",
  "completed",
  "cancelled",
] as const;

export const CreateIssuedOrderSchema = z.object({
  po_number: z.string().max(50).nullish(),
  customer_id: nullableIntIdFromForm.nullish(),
  status: z.enum(ISSUED_ORDER_STATUSES).optional(),
  currency: z.string().max(10).optional(),
  vat_rate: numberInRange(0, 100).optional(),
  apply_vat: booleanFromForm.optional(),
  exchange_rate: nonNegativeNumberFromForm.optional(),
  order_date: isoDateString.nullish(),
  delivery_date: isoDateString.nullish(),
  language: z.string().max(5).optional(),
  delivery_terms: z.string().max(500).nullish(),
  payment_terms: z.string().max(500).nullish(),
  issued_by: z.string().max(255).nullish(),
  notes: z.string().nullish(),
  internal_notes: z.string().nullish(),
  items: z.array(IssuedOrderItemSchema).optional(),
});

export const UpdateIssuedOrderSchema = CreateIssuedOrderSchema.partial();
