import { z } from "zod/v4";

export const InvoiceItemFormSchema = z.object({
  is_non_valued: z.boolean(),

  description: z.string().max(2000).optional().default(""),
  quantity: z.any(), //NumericStringSchema.optional(),
  unit_amount: z.any(), //NumericStringSchema.optional(),

  subtotal_amount: z.any(), //z.number(),
  discount_percentage: z.any(), //NumericStringSchema.optional(),
  discount_amount: z.number(),
  taxable_amount: z.number(),

  tax_codes: z.array(z.string()).default([]),

  taxes_amount: z.number(),
  total_amount: z.number(),
});

export const InvoiceFormSchema = z.object({
  invoice_number: z.string().optional(),
  series: z.string().optional(),

  invoice_date: z.string().optional(),
  operation_date: z.string().optional(),

  customer_id: z.string().optional(),
  recipient: z
    .object({
      id: z.string().optional(),
      name: z.string().optional(),
      tin: z.string().optional(),
      street: z.string().optional(),
      street2: z.string().optional(),
      city: z.string().optional(),
      province: z.string().optional(),
      postal_code: z.string().optional(),
      country: z.string().optional(),
    })
    .optional(),

  reference: z.string().optional(),
  description: z.string().optional(),
  notes: z.string().optional(),

  language_code: z
    .string({
      error: "El idioma es obligatorio",
    })
    .min(1, "Debe indicar un idioma")
    .toUpperCase() // asegura mayúsculas
    .default("es"),

  currency_code: z
    .string({
      error: "La moneda es obligatoria",
    })
    .min(1, "La moneda no puede estar vacía")
    .toUpperCase() // asegura mayúsculas
    .default("EUR"),

  taxes: z
    .array(
      z.object({
        tax_code: z.string(),
        tax_label: z.string(),
        taxable_amount: z.number(),
        taxes_amount: z.number(),
      })
    )
    .optional(),

  items: z.array(InvoiceItemFormSchema).optional(),

  subtotal_amount: z.number(),
  discount_percentage: z.number(),
  discount_amount: z.number(),
  taxable_amount: z.number(),
  taxes_amount: z.number(),
  total_amount: z.number(),
});

export type InvoiceFormData = z.infer<typeof InvoiceFormSchema>;
export type InvoiceItemFormData = z.infer<typeof InvoiceItemFormSchema>;

export const defaultCustomerInvoiceItemFormData: InvoiceItemFormData = {
  is_non_valued: false,
  description: "",
  quantity: "",
  unit_amount: "",
  subtotal_amount: 0,
  discount_percentage: "",
  discount_amount: 0,
  taxable_amount: 0,
  tax_codes: ["iva_21"],
  taxes_amount: 0,
  total_amount: 0,
};

export const defaultCustomerInvoiceFormData: InvoiceFormData = {
  invoice_number: "",
  series: "",

  invoice_date: "",
  operation_date: "",

  reference: "",
  description: "",
  notes: "",

  language_code: "es",
  currency_code: "EUR",

  items: [],

  subtotal_amount: 0,
  discount_amount: 0,
  discount_percentage: 0,
  taxable_amount: 0,
  taxes_amount: 0,
  total_amount: 0,
};
