import { registerCommand } from "@open-mercato/shared/lib/commands";
import { SalesSettings } from "../data/entities.js";
import { salesSettingsUpsertSchema } from "../data/validators.js";
import { ensureOrganizationScope, ensureTenantScope } from "./shared.js";
async function loadSalesSettings(em, params) {
  return em.findOne(SalesSettings, {
    tenantId: params.tenantId,
    organizationId: params.organizationId
  });
}
const saveSalesSettingsCommand = {
  id: "sales.settings.save",
  async execute(rawInput, ctx) {
    const input = salesSettingsUpsertSchema.parse(rawInput);
    ensureTenantScope(ctx, input.tenantId);
    ensureOrganizationScope(ctx, input.organizationId);
    const em = ctx.container.resolve("em").fork();
    let settings = await loadSalesSettings(em, {
      tenantId: input.tenantId,
      organizationId: input.organizationId
    });
    const orderFormat = input.orderNumberFormat.trim();
    const quoteFormat = input.quoteNumberFormat.trim();
    if (!settings) {
      settings = em.create(SalesSettings, {
        tenantId: input.tenantId,
        organizationId: input.organizationId,
        orderNumberFormat: orderFormat,
        quoteNumberFormat: quoteFormat,
        orderCustomerEditableStatuses: input.orderCustomerEditableStatuses ?? null,
        orderAddressEditableStatuses: input.orderAddressEditableStatuses ?? null
      });
      em.persist(settings);
    } else {
      settings.orderNumberFormat = orderFormat;
      settings.quoteNumberFormat = quoteFormat;
      if (input.orderCustomerEditableStatuses !== void 0) {
        settings.orderCustomerEditableStatuses = input.orderCustomerEditableStatuses ?? null;
      }
      if (input.orderAddressEditableStatuses !== void 0) {
        settings.orderAddressEditableStatuses = input.orderAddressEditableStatuses ?? null;
      }
      settings.updatedAt = /* @__PURE__ */ new Date();
    }
    await em.flush();
    const generator = ctx.container.resolve("salesDocumentNumberGenerator");
    if (input.orderNextNumber) {
      await generator.setNextSequence("order", input, input.orderNextNumber);
    }
    if (input.quoteNextNumber) {
      await generator.setNextSequence("quote", input, input.quoteNextNumber);
    }
    const sequences = await generator.peekSequences(input);
    return {
      settingsId: settings.id,
      orderNumberFormat: settings.orderNumberFormat,
      quoteNumberFormat: settings.quoteNumberFormat,
      nextOrderNumber: sequences.order,
      nextQuoteNumber: sequences.quote,
      orderCustomerEditableStatuses: settings.orderCustomerEditableStatuses ?? null,
      orderAddressEditableStatuses: settings.orderAddressEditableStatuses ?? null
    };
  }
};
registerCommand(saveSalesSettingsCommand);
export {
  loadSalesSettings
};
//# sourceMappingURL=settings.js.map
