import { z } from "zod";
import {
  createDictionaryEntrySchema,
  updateDictionaryEntrySchema
} from "@open-mercato/core/modules/dictionaries/data/validators";
import { getPaymentProvider, getShippingProvider } from "../lib/providers/index.js";
import { REFERENCE_UNIT_CODES } from "@open-mercato/shared/lib/units/unitCodes";
import { isValidPhoneNumber } from "@open-mercato/shared/lib/phone";
const SALES_PHONE_INVALID_MESSAGE_KEY = "customers.people.form.primaryPhone.invalid";
const optionalPhoneField = (max = 50) => z.string().trim().max(max).refine((val) => isValidPhoneNumber(val), { message: SALES_PHONE_INVALID_MESSAGE_KEY }).optional();
const optionalNullablePhoneField = (max = 50) => z.union([
  z.string().trim().max(max).refine((val) => isValidPhoneNumber(val), { message: SALES_PHONE_INVALID_MESSAGE_KEY }),
  z.literal(""),
  z.null()
]).optional();
const customerSnapshotSchema = z.object({
  customer: z.object({
    primaryPhone: optionalNullablePhoneField()
  }).passthrough().nullable().optional(),
  contact: z.unknown().optional()
}).passthrough();
const uuid = () => z.string().uuid();
const scoped = z.object({
  organizationId: uuid(),
  tenantId: uuid()
});
const currencyCode = z.string().trim().regex(/^[A-Z]{3}$/, "currency code must be a three-letter ISO code");
const decimal = (opts) => {
  let schema = z.coerce.number();
  if (typeof opts?.min === "number") schema = schema.min(opts.min);
  if (typeof opts?.max === "number") schema = schema.max(opts.max, opts.message);
  return schema;
};
const MAX_QUANTITY = 999999999;
const percentage = () => decimal({ min: 0, max: 100 });
const jsonRecord = z.record(z.string(), z.unknown());
const metadata = jsonRecord.optional();
const providerSettings = jsonRecord.optional();
const channelCodeSchema = z.string().trim().toLowerCase().regex(/^[a-z0-9\-_]+$/).max(120);
const numberFormatSchema = z.string().trim().min(1).max(191);
const statusListSchema = z.array(z.string().trim().min(1).max(120)).max(200).optional().nullable();
const salesSettingsUpsertSchema = scoped.extend({
  orderNumberFormat: numberFormatSchema,
  quoteNumberFormat: numberFormatSchema,
  orderNextNumber: z.coerce.number().int().min(1).max(1e9).optional(),
  quoteNextNumber: z.coerce.number().int().min(1).max(1e9).optional(),
  orderCustomerEditableStatuses: statusListSchema,
  orderAddressEditableStatuses: statusListSchema
});
const salesEditingSettingsSchema = scoped.extend({
  orderNumberFormat: numberFormatSchema.optional(),
  quoteNumberFormat: numberFormatSchema.optional(),
  orderCustomerEditableStatuses: statusListSchema,
  orderAddressEditableStatuses: statusListSchema
});
const channelCreateSchema = scoped.extend({
  name: z.string().trim().min(1).max(255),
  code: channelCodeSchema,
  description: z.string().trim().max(2e3).optional(),
  statusEntryId: uuid().optional(),
  websiteUrl: z.string().trim().url().max(300).optional(),
  contactEmail: z.string().trim().email().max(320).optional(),
  contactPhone: optionalPhoneField(),
  addressLine1: z.string().trim().max(255).optional(),
  addressLine2: z.string().trim().max(255).optional(),
  city: z.string().trim().max(120).optional(),
  region: z.string().trim().max(120).optional(),
  postalCode: z.string().trim().max(30).optional(),
  country: z.string().trim().max(2).optional(),
  latitude: decimal().optional(),
  longitude: decimal().optional(),
  isActive: z.boolean().optional(),
  metadata
});
const channelUpdateSchema = z.object({
  id: uuid(),
  code: channelCodeSchema
}).merge(channelCreateSchema.omit({ code: true }).partial());
const shippingMethodBaseSchema = scoped.extend({
  name: z.string().trim().min(1).max(255),
  code: z.string().trim().toLowerCase().regex(/^[a-z0-9\-_]+$/).max(120),
  description: z.string().trim().max(2e3).optional(),
  carrierCode: z.string().trim().max(120).optional(),
  providerKey: z.string().trim().max(120).optional(),
  serviceLevel: z.string().trim().max(120).optional(),
  estimatedTransitDays: z.coerce.number().int().min(0).max(365).optional(),
  baseRateNet: decimal({ min: 0 }).optional(),
  baseRateGross: decimal({ min: 0 }).optional(),
  currencyCode: currencyCode.optional(),
  isActive: z.boolean().optional(),
  providerSettings,
  metadata
});
const shippingMethodRefine = (value, ctx) => {
  if (value.providerKey) {
    const provider = getShippingProvider(value.providerKey);
    const schema = provider?.settings?.schema;
    if (schema) {
      const parsed = schema.safeParse(value.providerSettings ?? {});
      if (!parsed.success) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: parsed.error.issues?.[0]?.message ?? "Invalid provider configuration",
          path: ["providerSettings"]
        });
      }
    }
  }
};
const shippingMethodCreateSchema = shippingMethodBaseSchema.superRefine(shippingMethodRefine);
const shippingMethodUpdateSchema = z.object({
  id: uuid()
}).merge(shippingMethodBaseSchema.partial()).superRefine(shippingMethodRefine);
const deliveryWindowCreateSchema = scoped.extend({
  name: z.string().trim().min(1).max(255),
  code: z.string().trim().toLowerCase().regex(/^[a-z0-9\-_]+$/).max(120),
  description: z.string().trim().max(2e3).optional(),
  leadTimeDays: z.coerce.number().int().min(0).max(365).optional(),
  cutoffTime: z.string().trim().regex(/^\d{2}:\d{2}$/).optional(),
  timezone: z.string().trim().max(120).optional(),
  isActive: z.boolean().optional(),
  metadata
});
const deliveryWindowUpdateSchema = z.object({
  id: uuid()
}).merge(deliveryWindowCreateSchema.partial());
const paymentMethodBaseSchema = scoped.extend({
  name: z.string().trim().min(1).max(255),
  code: z.string().trim().toLowerCase().regex(/^[a-z0-9\-_]+$/).max(120),
  description: z.string().trim().max(2e3).optional(),
  providerKey: z.string().trim().max(120).optional(),
  terms: z.string().trim().max(4e3).optional(),
  isActive: z.boolean().optional(),
  providerSettings,
  metadata
});
const paymentMethodRefine = (value, ctx) => {
  if (value.providerKey) {
    const provider = getPaymentProvider(value.providerKey);
    const schema = provider?.settings?.schema;
    if (schema) {
      const parsed = schema.safeParse(value.providerSettings ?? {});
      if (!parsed.success) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: parsed.error.issues?.[0]?.message ?? "Invalid provider configuration",
          path: ["providerSettings"]
        });
      }
    }
  }
};
const paymentMethodCreateSchema = paymentMethodBaseSchema.superRefine(paymentMethodRefine);
const paymentMethodUpdateSchema = z.object({
  id: uuid()
}).merge(paymentMethodBaseSchema.partial()).superRefine(paymentMethodRefine);
const salesTagCreateSchema = scoped.extend({
  slug: z.string().trim().min(1).max(80).regex(/^[a-z0-9_-]+$/, "Slug must be lowercase and may contain dashes or underscores"),
  label: z.string().trim().min(1).max(120),
  color: z.string().trim().max(30).optional(),
  description: z.string().trim().max(400).optional()
});
const salesTagUpdateSchema = z.object({
  id: uuid()
}).merge(salesTagCreateSchema.partial());
const taxRateCreateSchema = scoped.extend({
  name: z.string().trim().min(1).max(255),
  code: z.string().trim().toLowerCase().regex(/^[a-z0-9\-_]+$/).max(120),
  rate: percentage(),
  countryCode: z.string().trim().length(2).optional(),
  regionCode: z.string().trim().max(6).optional(),
  postalCode: z.string().trim().max(30).optional(),
  city: z.string().trim().max(120).optional(),
  customerGroupId: uuid().optional(),
  productCategoryId: uuid().optional(),
  channelId: uuid().optional(),
  priority: z.coerce.number().int().min(0).max(10).optional(),
  isCompound: z.boolean().optional(),
  isDefault: z.boolean().optional(),
  metadata,
  startsAt: z.coerce.date().optional(),
  endsAt: z.coerce.date().optional()
});
const taxRateUpdateSchema = z.object({
  id: uuid()
}).merge(taxRateCreateSchema.partial());
const statusDictionaryEntryCreateSchema = z.object({
  value: createDictionaryEntrySchema.shape.value,
  label: z.string().trim().min(1).max(150).optional(),
  color: createDictionaryEntrySchema.shape.color,
  icon: createDictionaryEntrySchema.shape.icon
});
const statusDictionaryEntryUpdateFieldsSchema = z.object({
  value: updateDictionaryEntrySchema.shape.value,
  label: z.string().trim().min(1).max(150).optional(),
  color: updateDictionaryEntrySchema.shape.color,
  icon: updateDictionaryEntrySchema.shape.icon
});
const validateStatusDictionaryUpdate = (payload) => Object.values(payload).some((value) => value !== void 0);
const statusDictionaryEntryUpdateSchema = statusDictionaryEntryUpdateFieldsSchema.refine(
  validateStatusDictionaryUpdate,
  { message: "Provide at least one field to update." }
);
const statusDictionaryCreateSchema = scoped.merge(statusDictionaryEntryCreateSchema);
const statusDictionaryUpdateSchema = scoped.merge(statusDictionaryEntryUpdateFieldsSchema).safeExtend({ id: uuid() }).refine(validateStatusDictionaryUpdate, { message: "Provide at least one field to update." });
const lineKindSchema = z.enum(["product", "service", "shipping", "discount", "adjustment"]);
const adjustmentKindSchema = z.string().trim().min(1).max(150);
const linePricingSchema = z.object({
  quantity: decimal({ min: 0, max: MAX_QUANTITY, message: "Quantity is too large." }),
  quantityUnit: z.string().trim().max(25).optional(),
  normalizedQuantity: decimal({ min: 0, max: MAX_QUANTITY, message: "Quantity is too large." }).optional(),
  normalizedUnit: z.string().trim().max(25).nullable().optional(),
  unitPriceNet: decimal({ min: 0 }).optional(),
  unitPriceGross: decimal({ min: 0 }).optional(),
  priceId: uuid().optional(),
  priceMode: z.enum(["net", "gross"]).optional(),
  taxRateId: uuid().optional(),
  discountAmount: decimal({ min: 0 }).optional(),
  discountPercent: percentage().optional(),
  taxRate: percentage().optional(),
  taxAmount: decimal({ min: 0 }).optional(),
  totalNetAmount: decimal({ min: 0 }).optional(),
  totalGrossAmount: decimal({ min: 0 }).optional()
});
const uomSnapshotSchema = z.object({
  version: z.literal(1),
  productId: z.string().nullable(),
  productVariantId: z.string().nullable(),
  baseUnitCode: z.string().nullable(),
  enteredUnitCode: z.string().nullable(),
  enteredQuantity: z.string(),
  toBaseFactor: z.string(),
  normalizedQuantity: z.string(),
  rounding: z.object({
    mode: z.enum(["half_up", "down", "up"]),
    scale: z.number().int()
  }),
  source: z.object({
    conversionId: z.string().nullable(),
    resolvedAt: z.string()
  }),
  unitPriceReference: z.object({
    enabled: z.boolean(),
    referenceUnitCode: z.enum(REFERENCE_UNIT_CODES).nullable(),
    baseQuantity: z.string().nullable(),
    grossPerReference: z.string().nullable().optional(),
    netPerReference: z.string().nullable().optional()
  }).optional()
}).nullable().optional();
const lineSharedSchema = z.object({
  kind: lineKindSchema.optional(),
  statusEntryId: uuid().optional(),
  productId: uuid().optional(),
  productVariantId: uuid().optional(),
  name: z.string().trim().max(255).optional(),
  description: z.string().trim().max(4e3).optional(),
  comment: z.string().trim().max(2e3).optional(),
  currencyCode,
  configuration: z.record(z.string(), z.unknown()).optional(),
  promotionCode: z.string().trim().max(120).optional(),
  promotionSnapshot: z.record(z.string(), z.unknown()).optional(),
  uomSnapshot: uomSnapshotSchema,
  metadata,
  customFieldSetId: uuid().optional(),
  customFields: z.record(z.string(), z.unknown()).optional()
});
const orderLineCreateSchema = scoped.extend({
  orderId: uuid(),
  lineNumber: z.coerce.number().int().min(0).optional(),
  ...lineSharedSchema.shape,
  ...linePricingSchema.shape,
  catalogSnapshot: z.record(z.string(), z.unknown()).optional()
});
const orderLineUpdateSchema = z.object({
  id: uuid()
}).merge(orderLineCreateSchema.partial());
const quoteLineCreateSchema = scoped.extend({
  quoteId: uuid(),
  lineNumber: z.coerce.number().int().min(0).optional(),
  ...lineSharedSchema.shape,
  ...linePricingSchema.shape,
  catalogSnapshot: z.record(z.string(), z.unknown()).optional()
});
const quoteLineUpdateSchema = z.object({
  id: uuid()
}).merge(quoteLineCreateSchema.partial());
const RETURN_ADJUSTMENT_POSITIVE_NET_MESSAGE = "Return adjustments must use a non-positive amountNet (returns reduce the total).";
const RETURN_ADJUSTMENT_POSITIVE_GROSS_MESSAGE = "Return adjustments must use a non-positive amountGross (returns reduce the total).";
const RETURN_ADJUSTMENT_ZERO_MESSAGE = "Return adjustments must use a non-zero amount. Create the return through the Returns tab instead of recording a zero-value Return adjustment.";
const DISCOUNT_ADJUSTMENT_NEGATIVE_NET_MESSAGE = "Discount adjustments must use a non-negative amountNet (discounts reduce the total).";
const DISCOUNT_ADJUSTMENT_NEGATIVE_GROSS_MESSAGE = "Discount adjustments must use a non-negative amountGross (discounts reduce the total).";
const SURCHARGE_ADJUSTMENT_NEGATIVE_NET_MESSAGE = "Surcharge adjustments must use a non-negative amountNet (surcharges add to the total).";
const SURCHARGE_ADJUSTMENT_NEGATIVE_GROSS_MESSAGE = "Surcharge adjustments must use a non-negative amountGross (surcharges add to the total).";
const SHIPPING_ADJUSTMENT_NEGATIVE_NET_MESSAGE = "Shipping adjustments must use a non-negative amountNet (shipping adds to the total).";
const SHIPPING_ADJUSTMENT_NEGATIVE_GROSS_MESSAGE = "Shipping adjustments must use a non-negative amountGross (shipping adds to the total).";
const TAX_ADJUSTMENT_NEGATIVE_NET_MESSAGE = "Tax adjustments must use a non-negative amountNet (taxes add to the total).";
const TAX_ADJUSTMENT_NEGATIVE_GROSS_MESSAGE = "Tax adjustments must use a non-negative amountGross (taxes add to the total).";
const NON_NEGATIVE_SIGN_MESSAGES = {
  discount: {
    net: DISCOUNT_ADJUSTMENT_NEGATIVE_NET_MESSAGE,
    gross: DISCOUNT_ADJUSTMENT_NEGATIVE_GROSS_MESSAGE
  },
  surcharge: {
    net: SURCHARGE_ADJUSTMENT_NEGATIVE_NET_MESSAGE,
    gross: SURCHARGE_ADJUSTMENT_NEGATIVE_GROSS_MESSAGE
  },
  shipping: {
    net: SHIPPING_ADJUSTMENT_NEGATIVE_NET_MESSAGE,
    gross: SHIPPING_ADJUSTMENT_NEGATIVE_GROSS_MESSAGE
  },
  tax: {
    net: TAX_ADJUSTMENT_NEGATIVE_NET_MESSAGE,
    gross: TAX_ADJUSTMENT_NEGATIVE_GROSS_MESSAGE
  }
};
const enforceAdjustmentSign = (value, ctx) => {
  if (!value.kind) return;
  if (value.kind === "return") {
    const netIsPositive = typeof value.amountNet === "number" && value.amountNet > 0;
    const grossIsPositive = typeof value.amountGross === "number" && value.amountGross > 0;
    if (netIsPositive) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: RETURN_ADJUSTMENT_POSITIVE_NET_MESSAGE,
        path: ["amountNet"]
      });
    }
    if (grossIsPositive) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: RETURN_ADJUSTMENT_POSITIVE_GROSS_MESSAGE,
        path: ["amountGross"]
      });
    }
    if (!netIsPositive && !grossIsPositive) {
      const netIsNegative = typeof value.amountNet === "number" && value.amountNet < 0;
      const grossIsNegative = typeof value.amountGross === "number" && value.amountGross < 0;
      if (!netIsNegative && !grossIsNegative) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: RETURN_ADJUSTMENT_ZERO_MESSAGE,
          path: ["amountNet"]
        });
      }
    }
    return;
  }
  const messages = NON_NEGATIVE_SIGN_MESSAGES[value.kind];
  if (!messages) return;
  if (typeof value.amountNet === "number" && value.amountNet < 0) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: messages.net,
      path: ["amountNet"]
    });
  }
  if (typeof value.amountGross === "number" && value.amountGross < 0) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: messages.gross,
      path: ["amountGross"]
    });
  }
};
const enforceReturnAdjustmentSign = enforceAdjustmentSign;
const RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE = "Return adjustment amountNet exceeds the remaining grand total. Reduce the amount or remove existing returns first.";
const RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE = "Return adjustment amountGross exceeds the remaining grand total. Reduce the amount or remove existing returns first.";
const RETURN_REMAINING_EPSILON = 5e-3;
const validateReturnAdjustmentWithinRemaining = (value) => {
  if (value.kind !== "return") return [];
  const absNet = typeof value.amountNet === "number" ? Math.abs(value.amountNet) : 0;
  const absGross = typeof value.amountGross === "number" ? Math.abs(value.amountGross) : 0;
  const issues = [];
  if (absGross > value.remainingGross + RETURN_REMAINING_EPSILON) {
    issues.push({ path: "amountGross", message: RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE });
  }
  if (absNet > value.remainingNet + RETURN_REMAINING_EPSILON) {
    issues.push({ path: "amountNet", message: RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE });
  }
  return issues;
};
const orderAdjustmentCreateSchema = scoped.extend({
  orderId: uuid(),
  orderLineId: uuid().optional(),
  scope: z.enum(["order", "line"]).optional(),
  kind: adjustmentKindSchema.optional(),
  code: z.string().trim().max(120).optional(),
  label: z.string().trim().max(255).optional(),
  calculatorKey: z.string().trim().max(120).optional(),
  promotionId: uuid().optional(),
  rate: percentage().optional(),
  amountNet: decimal().optional(),
  amountGross: decimal().optional(),
  currencyCode: currencyCode.optional(),
  metadata,
  customFields: z.record(z.string(), z.unknown()).optional(),
  position: z.coerce.number().int().min(0).optional()
});
const orderAdjustmentUpdateSchema = z.object({
  id: uuid()
}).merge(orderAdjustmentCreateSchema.partial());
const quoteAdjustmentCreateSchema = scoped.extend({
  quoteId: uuid(),
  quoteLineId: uuid().optional(),
  scope: z.enum(["order", "line"]).optional(),
  kind: adjustmentKindSchema.optional(),
  code: z.string().trim().max(120).optional(),
  label: z.string().trim().max(255).optional(),
  calculatorKey: z.string().trim().max(120).optional(),
  promotionId: uuid().optional(),
  rate: percentage().optional(),
  amountNet: decimal().optional(),
  amountGross: decimal().optional(),
  currencyCode: currencyCode.optional(),
  metadata,
  customFields: z.record(z.string(), z.unknown()).optional(),
  position: z.coerce.number().int().min(0).optional()
});
const quoteAdjustmentUpdateSchema = z.object({
  id: uuid()
}).merge(quoteAdjustmentCreateSchema.partial());
const orderTotalsSchema = z.object({
  subtotalNetAmount: decimal({ min: 0 }).optional(),
  subtotalGrossAmount: decimal({ min: 0 }).optional(),
  discountTotalAmount: decimal({ min: 0 }).optional(),
  taxTotalAmount: decimal({ min: 0 }).optional(),
  shippingNetAmount: decimal({ min: 0 }).optional(),
  shippingGrossAmount: decimal({ min: 0 }).optional(),
  surchargeTotalAmount: decimal({ min: 0 }).optional(),
  grandTotalNetAmount: decimal({ min: 0 }).optional(),
  grandTotalGrossAmount: decimal({ min: 0 }).optional(),
  paidTotalAmount: decimal({ min: 0 }).optional(),
  refundedTotalAmount: decimal({ min: 0 }).optional(),
  outstandingAmount: decimal().optional(),
  lineItemCount: z.coerce.number().int().min(0).optional()
});
const quoteTotalsSchema = z.object({
  subtotalNetAmount: decimal({ min: 0 }).optional(),
  subtotalGrossAmount: decimal({ min: 0 }).optional(),
  discountTotalAmount: decimal({ min: 0 }).optional(),
  taxTotalAmount: decimal({ min: 0 }).optional(),
  grandTotalNetAmount: decimal({ min: 0 }).optional(),
  grandTotalGrossAmount: decimal({ min: 0 }).optional(),
  lineItemCount: z.coerce.number().int().min(0).optional()
});
const orderCreateSchema = scoped.extend({
  orderNumber: z.string().trim().min(1).max(191).optional(),
  externalReference: z.string().trim().max(191).optional(),
  customerReference: z.string().trim().max(191).optional(),
  customerEntityId: uuid().optional(),
  customerContactId: uuid().optional(),
  customerSnapshot: customerSnapshotSchema.optional(),
  billingAddressId: uuid().optional(),
  shippingAddressId: uuid().optional(),
  billingAddressSnapshot: jsonRecord.optional(),
  shippingAddressSnapshot: jsonRecord.optional(),
  currencyCode,
  exchangeRate: decimal({ min: 0 }).optional(),
  statusEntryId: uuid().optional(),
  fulfillmentStatusEntryId: uuid().optional(),
  paymentStatusEntryId: uuid().optional(),
  taxStrategyKey: z.string().trim().max(120).optional(),
  discountStrategyKey: z.string().trim().max(120).optional(),
  taxInfo: jsonRecord.optional(),
  shippingMethodId: uuid().optional(),
  shippingMethodCode: z.string().trim().max(120).optional(),
  deliveryWindowId: uuid().optional(),
  deliveryWindowCode: z.string().trim().max(120).optional(),
  paymentMethodId: uuid().optional(),
  paymentMethodCode: z.string().trim().max(120).optional(),
  channelId: uuid().optional(),
  placedAt: z.coerce.date().optional(),
  expectedDeliveryAt: z.coerce.date().optional(),
  dueAt: z.coerce.date().optional(),
  comments: z.string().trim().max(4e3).optional(),
  internalNotes: z.string().trim().max(4e3).optional(),
  shippingMethodSnapshot: jsonRecord.optional(),
  deliveryWindowSnapshot: jsonRecord.optional(),
  paymentMethodSnapshot: jsonRecord.optional(),
  metadata,
  customFieldSetId: uuid().optional(),
  lines: z.array(orderLineCreateSchema.omit({ organizationId: true, tenantId: true, orderId: true })).optional(),
  adjustments: z.array(orderAdjustmentCreateSchema.omit({ organizationId: true, tenantId: true, orderId: true })).optional(),
  tags: z.array(uuid()).optional(),
  ...orderTotalsSchema.shape
});
const orderUpdateSchema = z.object({
  id: uuid()
}).merge(orderCreateSchema.partial());
const quoteCreateSchema = scoped.extend({
  quoteNumber: z.string().trim().min(1).max(191).optional(),
  statusEntryId: uuid().optional(),
  customerEntityId: uuid().optional(),
  customerContactId: uuid().optional(),
  channelId: uuid().optional(),
  customerSnapshot: customerSnapshotSchema.optional(),
  billingAddressId: uuid().optional(),
  shippingAddressId: uuid().optional(),
  billingAddressSnapshot: jsonRecord.optional(),
  shippingAddressSnapshot: jsonRecord.optional(),
  currencyCode,
  validFrom: z.coerce.date().optional(),
  validUntil: z.coerce.date().optional(),
  comments: z.string().trim().max(4e3).optional(),
  taxInfo: jsonRecord.optional(),
  shippingMethodId: uuid().optional(),
  shippingMethodCode: z.string().trim().max(120).optional(),
  deliveryWindowId: uuid().optional(),
  deliveryWindowCode: z.string().trim().max(120).optional(),
  paymentMethodId: uuid().optional(),
  paymentMethodCode: z.string().trim().max(120).optional(),
  shippingMethodSnapshot: jsonRecord.optional(),
  deliveryWindowSnapshot: jsonRecord.optional(),
  paymentMethodSnapshot: jsonRecord.optional(),
  metadata,
  customFieldSetId: uuid().optional(),
  lines: z.array(quoteLineCreateSchema.omit({ organizationId: true, tenantId: true, quoteId: true })).optional(),
  adjustments: z.array(quoteAdjustmentCreateSchema.omit({ organizationId: true, tenantId: true, quoteId: true })).optional(),
  tags: z.array(uuid()).optional(),
  ...quoteTotalsSchema.shape
});
const quoteUpdateSchema = z.object({
  id: uuid()
}).merge(quoteCreateSchema.partial());
const documentKind = z.enum(["order", "quote"]);
const documentAddressFields = {
  documentId: uuid(),
  documentKind,
  customerAddressId: uuid().optional(),
  name: z.string().trim().max(255).nullable().optional(),
  purpose: z.string().trim().max(120).nullable().optional(),
  companyName: z.string().trim().max(255).nullable().optional(),
  addressLine1: z.string().trim().min(1).max(255),
  addressLine2: z.string().trim().max(255).nullable().optional(),
  city: z.string().trim().max(120).nullable().optional(),
  region: z.string().trim().max(120).nullable().optional(),
  postalCode: z.string().trim().max(60).nullable().optional(),
  country: z.string().trim().max(2).nullable().optional(),
  buildingNumber: z.string().trim().max(60).nullable().optional(),
  flatNumber: z.string().trim().max(60).nullable().optional(),
  latitude: z.coerce.number().optional().nullable(),
  longitude: z.coerce.number().optional().nullable()
};
const documentAddressCreateSchema = scoped.extend(documentAddressFields);
const documentAddressUpdateSchema = scoped.extend({
  id: uuid(),
  ...documentAddressFields
});
const documentAddressDeleteSchema = scoped.extend({
  id: uuid(),
  documentId: uuid(),
  documentKind
});
const shipmentCreateSchema = scoped.extend({
  orderId: uuid(),
  shipmentNumber: z.string().trim().max(191).optional(),
  shippingMethodId: uuid().optional(),
  statusEntryId: uuid().optional(),
  documentStatusEntryId: uuid().optional(),
  lineStatusEntryId: uuid().optional(),
  carrierName: z.string().trim().max(191).optional(),
  trackingNumbers: z.array(z.string().trim().max(191)).optional(),
  shippedAt: z.coerce.date().optional(),
  deliveredAt: z.coerce.date().optional(),
  weightValue: decimal({ min: 0 }).optional(),
  weightUnit: z.string().trim().max(25).optional(),
  declaredValueNet: decimal({ min: 0 }).optional(),
  declaredValueGross: decimal({ min: 0 }).optional(),
  currencyCode: currencyCode.optional(),
  notes: z.string().trim().max(4e3).optional(),
  metadata,
  shipmentAddressSnapshot: jsonRecord.optional(),
  customFields: z.record(z.string(), z.unknown()).optional(),
  items: z.array(
    z.object({
      orderLineId: uuid(),
      quantity: decimal({ min: 0, max: MAX_QUANTITY, message: "Quantity is too large." }).int("Quantity must be a whole number."),
      metadata
    })
  ).optional()
});
const shipmentUpdateSchema = z.object({
  id: uuid()
}).merge(shipmentCreateSchema.partial());
const returnLineQuantitySchema = z.coerce.number().int("Return quantity must be a whole number.").min(1, "Return quantity must be at least 1.").max(MAX_QUANTITY, "Quantity is too large.");
const RETURN_DATE_IN_FUTURE_MESSAGE = "Return date cannot be in the future.";
const returnedAtSchema = z.coerce.date().refine((value) => value.getTime() <= Date.now(), {
  message: RETURN_DATE_IN_FUTURE_MESSAGE
}).optional();
const returnCreateSchema = scoped.extend({
  orderId: uuid(),
  reason: z.string().trim().max(4e3).optional(),
  notes: z.string().trim().max(4e3).optional(),
  returnedAt: returnedAtSchema,
  lines: z.array(
    z.object({
      orderLineId: uuid(),
      quantity: returnLineQuantitySchema
    })
  ).min(1)
});
const returnUpdateSchema = scoped.extend({
  id: uuid(),
  orderId: uuid(),
  reason: z.string().trim().max(4e3).optional(),
  notes: z.string().trim().max(4e3).optional(),
  returnedAt: returnedAtSchema
});
const returnDeleteSchema = scoped.extend({
  id: uuid(),
  orderId: uuid()
});
const invoiceCreateSchema = scoped.extend({
  orderId: uuid().optional(),
  invoiceNumber: z.string().trim().min(1).max(191).optional(),
  statusEntryId: uuid().optional(),
  issueDate: z.coerce.date().optional(),
  dueDate: z.coerce.date().optional(),
  currencyCode,
  metadata,
  customFieldSetId: uuid().optional(),
  lines: z.array(
    z.object({
      orderLineId: uuid().optional(),
      lineNumber: z.coerce.number().int().min(0).optional(),
      kind: lineKindSchema.optional(),
      name: z.string().trim().max(500).optional(),
      sku: z.string().trim().max(191).optional(),
      description: z.string().trim().max(4e3).optional(),
      quantity: decimal({ min: 0, max: MAX_QUANTITY, message: "Quantity is too large." }),
      quantityUnit: z.string().trim().max(25).optional(),
      normalizedQuantity: decimal({ min: 0, max: MAX_QUANTITY, message: "Quantity is too large." }).optional(),
      normalizedUnit: z.string().trim().max(25).nullable().optional(),
      uomSnapshot: uomSnapshotSchema,
      currencyCode,
      unitPriceNet: decimal({ min: 0 }).optional(),
      unitPriceGross: decimal({ min: 0 }).optional(),
      discountAmount: decimal({ min: 0 }).optional(),
      discountPercent: percentage().optional(),
      taxRate: percentage().optional(),
      taxAmount: decimal({ min: 0 }).optional(),
      totalNetAmount: decimal({ min: 0 }).optional(),
      totalGrossAmount: decimal({ min: 0 }).optional(),
      metadata
    })
  ).optional(),
  subtotalNetAmount: decimal({ min: 0 }).optional(),
  subtotalGrossAmount: decimal({ min: 0 }).optional(),
  discountTotalAmount: decimal({ min: 0 }).optional(),
  taxTotalAmount: decimal({ min: 0 }).optional(),
  grandTotalNetAmount: decimal({ min: 0 }).optional(),
  grandTotalGrossAmount: decimal({ min: 0 }).optional(),
  paidTotalAmount: decimal({ min: 0 }).optional(),
  outstandingAmount: decimal().optional()
});
const invoiceUpdateSchema = z.object({
  id: uuid()
}).merge(invoiceCreateSchema.partial());
const creditMemoCreateSchema = scoped.extend({
  orderId: uuid().optional(),
  invoiceId: uuid().optional(),
  creditMemoNumber: z.string().trim().min(1).max(191).optional(),
  statusEntryId: uuid().optional(),
  issueDate: z.coerce.date().optional(),
  reason: z.string().trim().max(4e3).optional(),
  currencyCode,
  metadata,
  customFieldSetId: uuid().optional(),
  lines: z.array(
    z.object({
      orderLineId: uuid().optional(),
      lineNumber: z.coerce.number().int().min(0).optional(),
      name: z.string().trim().max(500).optional(),
      sku: z.string().trim().max(191).optional(),
      description: z.string().trim().max(4e3).optional(),
      quantity: decimal({ min: 0, max: MAX_QUANTITY, message: "Quantity is too large." }),
      quantityUnit: z.string().trim().max(25).optional(),
      normalizedQuantity: decimal({ min: 0, max: MAX_QUANTITY, message: "Quantity is too large." }).optional(),
      normalizedUnit: z.string().trim().max(25).nullable().optional(),
      uomSnapshot: uomSnapshotSchema,
      currencyCode,
      unitPriceNet: decimal({ min: 0 }).optional(),
      unitPriceGross: decimal({ min: 0 }).optional(),
      taxRate: percentage().optional(),
      taxAmount: decimal({ min: 0 }).optional(),
      totalNetAmount: decimal({ min: 0 }).optional(),
      totalGrossAmount: decimal({ min: 0 }).optional(),
      metadata
    })
  ).optional(),
  subtotalNetAmount: decimal({ min: 0 }).optional(),
  subtotalGrossAmount: decimal({ min: 0 }).optional(),
  taxTotalAmount: decimal({ min: 0 }).optional(),
  grandTotalNetAmount: decimal({ min: 0 }).optional(),
  grandTotalGrossAmount: decimal({ min: 0 }).optional()
});
const creditMemoUpdateSchema = z.object({
  id: uuid()
}).merge(creditMemoCreateSchema.partial());
const paymentCreateSchema = scoped.extend({
  orderId: uuid().optional(),
  paymentMethodId: uuid().optional(),
  paymentReference: z.string().trim().max(191).optional(),
  statusEntryId: uuid().optional(),
  documentStatusEntryId: uuid().optional(),
  lineStatusEntryId: uuid().optional(),
  amount: decimal({ min: 0 }),
  currencyCode,
  capturedAmount: decimal({ min: 0 }).optional(),
  refundedAmount: decimal({ min: 0 }).optional(),
  receivedAt: z.coerce.date().optional(),
  capturedAt: z.coerce.date().optional(),
  metadata,
  customFieldSetId: uuid().optional(),
  customFields: z.record(z.string(), z.unknown()).optional(),
  allocations: z.array(
    z.object({
      orderId: uuid().optional(),
      invoiceId: uuid().optional(),
      amount: decimal({ min: 0 }),
      currencyCode,
      metadata
    })
  ).optional()
});
const paymentUpdateSchema = z.object({
  id: uuid()
}).merge(paymentCreateSchema.partial());
const noteCreateSchema = scoped.extend({
  contextType: z.enum(["order", "quote", "invoice", "credit_memo"]),
  contextId: uuid(),
  orderId: uuid().optional(),
  quoteId: uuid().optional(),
  authorUserId: uuid().optional(),
  body: z.string().trim().min(1).max(8e3),
  appearanceIcon: z.string().trim().max(100).optional().nullable(),
  appearanceColor: z.string().trim().regex(/^#([0-9a-fA-F]{6})$/).optional().nullable()
});
const noteUpdateSchema = z.object({
  id: uuid()
}).merge(
  z.object({
    body: z.string().trim().min(1).max(8e3).optional()
  }).extend({
    authorUserId: uuid().optional(),
    appearanceIcon: z.string().trim().max(100).optional().nullable(),
    appearanceColor: z.string().trim().regex(/^#([0-9a-fA-F]{6})$/).optional().nullable()
  })
);
const documentNumberRequestSchema = scoped.extend({
  kind: z.enum(["order", "quote", "invoice", "credit_memo"]),
  format: numberFormatSchema.optional()
});
const quoteSendSchema = z.object({
  quoteId: z.string().uuid(),
  validForDays: z.coerce.number().int().min(1).max(365).default(14)
});
const quoteAcceptSchema = z.object({
  token: z.string().uuid()
});
export {
  DISCOUNT_ADJUSTMENT_NEGATIVE_GROSS_MESSAGE,
  DISCOUNT_ADJUSTMENT_NEGATIVE_NET_MESSAGE,
  RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,
  RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE,
  RETURN_ADJUSTMENT_POSITIVE_GROSS_MESSAGE,
  RETURN_ADJUSTMENT_POSITIVE_NET_MESSAGE,
  RETURN_ADJUSTMENT_ZERO_MESSAGE,
  RETURN_DATE_IN_FUTURE_MESSAGE,
  SALES_PHONE_INVALID_MESSAGE_KEY,
  SHIPPING_ADJUSTMENT_NEGATIVE_GROSS_MESSAGE,
  SHIPPING_ADJUSTMENT_NEGATIVE_NET_MESSAGE,
  SURCHARGE_ADJUSTMENT_NEGATIVE_GROSS_MESSAGE,
  SURCHARGE_ADJUSTMENT_NEGATIVE_NET_MESSAGE,
  TAX_ADJUSTMENT_NEGATIVE_GROSS_MESSAGE,
  TAX_ADJUSTMENT_NEGATIVE_NET_MESSAGE,
  channelCreateSchema,
  channelUpdateSchema,
  creditMemoCreateSchema,
  creditMemoUpdateSchema,
  customerSnapshotSchema,
  deliveryWindowCreateSchema,
  deliveryWindowUpdateSchema,
  documentAddressCreateSchema,
  documentAddressDeleteSchema,
  documentAddressUpdateSchema,
  documentNumberRequestSchema,
  enforceAdjustmentSign,
  enforceReturnAdjustmentSign,
  invoiceCreateSchema,
  invoiceUpdateSchema,
  noteCreateSchema,
  noteUpdateSchema,
  orderAdjustmentCreateSchema,
  orderAdjustmentUpdateSchema,
  orderCreateSchema,
  orderLineCreateSchema,
  orderLineUpdateSchema,
  orderUpdateSchema,
  paymentCreateSchema,
  paymentMethodCreateSchema,
  paymentMethodUpdateSchema,
  paymentUpdateSchema,
  quoteAcceptSchema,
  quoteAdjustmentCreateSchema,
  quoteAdjustmentUpdateSchema,
  quoteCreateSchema,
  quoteLineCreateSchema,
  quoteLineUpdateSchema,
  quoteSendSchema,
  quoteUpdateSchema,
  returnCreateSchema,
  returnDeleteSchema,
  returnUpdateSchema,
  salesEditingSettingsSchema,
  salesSettingsUpsertSchema,
  salesTagCreateSchema,
  salesTagUpdateSchema,
  shipmentCreateSchema,
  shipmentUpdateSchema,
  shippingMethodCreateSchema,
  shippingMethodUpdateSchema,
  statusDictionaryCreateSchema,
  statusDictionaryUpdateSchema,
  taxRateCreateSchema,
  taxRateUpdateSchema,
  validateReturnAdjustmentWithinRemaining
};
//# sourceMappingURL=validators.js.map
