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

const QuotationItemSchema = z.object({
  description: z.string().max(8000).nullish(),
  item_description: z.string().max(8000).nullish(),
  quantity: positiveNumberFromForm.default(1),
  unit: z.string().max(255).nullish(),
  unit_price: numberFromForm.default(0),
  is_included_in_total: booleanFromForm.optional().default(true),
  position: nonNegativeNumberFromForm.optional(),
});

const ScopeSectionSchema = z.object({
  title: z.string().max(255).nullish(),
  title_cz: z.string().max(255).nullish(),
  content: z.string().max(8000).nullish(),
  position: nonNegativeNumberFromForm.optional(),
});

export const CreateQuotationSchema = z.object({
  quotation_number: z.string().max(255).nullish(),
  project_code: z.string().max(255).nullish(),
  customer_id: nullableIntIdFromForm.nullish(),
  created_at: z.string().max(255).nullish(),
  valid_until: z.string().max(255).nullish(),
  currency: z.string().max(20).optional().default("CZK"),
  language: z.string().max(20).optional().default("cs"),
  vat_rate: numberInRange(0, 100).optional().default(21.0),
  apply_vat: booleanFromForm.optional().default(true),
  status: z
    .enum(["active", "ordered", "invalidated"])
    .optional()
    .default("active"),
  scope_title: z.string().max(255).nullish(),
  scope_description: z.string().max(8000).nullish(),
  items: z.array(QuotationItemSchema).optional(),
  sections: z.array(ScopeSectionSchema).optional(),
});

export const UpdateQuotationSchema = z.object({
  project_code: z.string().max(255).nullish(),
  customer_id: nullableIntIdFromForm.optional(),
  created_at: z.union([z.string().max(255), z.null()]).optional(),
  valid_until: z.union([z.string().max(255), z.null()]).optional(),
  currency: z.string().max(20).optional(),
  language: z.string().max(20).optional(),
  vat_rate: numberInRange(0, 100).optional(),
  apply_vat: booleanFromForm.optional(),
  status: z.enum(["active", "ordered", "invalidated"]).optional(),
  scope_title: z.string().max(255).nullish(),
  scope_description: z.string().max(8000).nullish(),
  items: z.array(QuotationItemSchema).optional(),
  sections: z.array(ScopeSectionSchema).optional(),
});

export type CreateQuotationInput = z.infer<typeof CreateQuotationSchema>;
export type UpdateQuotationInput = z.infer<typeof UpdateQuotationSchema>;
