import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { SalesChannel, SalesOrder, SalesQuote } from "../data/entities.js";
function resolveCustomerName(snapshot) {
  if (!snapshot) return null;
  const customer = snapshot.customer;
  const contact = snapshot.contact;
  const displayName = typeof customer?.displayName === "string" ? customer.displayName : null;
  if (displayName && displayName.trim().length > 0) return displayName.trim();
  const first = typeof contact?.firstName === "string" ? contact.firstName : null;
  const last = typeof contact?.lastName === "string" ? contact.lastName : null;
  const preferred = typeof contact?.preferredName === "string" ? contact.preferredName : null;
  const parts = [preferred ?? first, last].map((part) => typeof part === "string" ? part.trim() : "").filter((part) => part.length > 0);
  return parts.length > 0 ? parts.join(" ") : null;
}
function formatTotal(amount, currency) {
  if (!amount) return null;
  const value = Number(amount);
  if (!Number.isFinite(value)) return currency ? `${amount} ${currency}` : amount;
  if (!currency) return value.toLocaleString();
  try {
    return new Intl.NumberFormat(void 0, { style: "currency", currency }).format(value);
  } catch {
    return `${value.toLocaleString()} ${currency}`;
  }
}
function statusColor(status) {
  if (!status) return void 0;
  const value = status.toLowerCase();
  if (value.includes("approved") || value.includes("paid") || value.includes("fulfilled") || value.includes("accepted")) {
    return "green";
  }
  if (value.includes("cancel") || value.includes("rejected") || value.includes("void")) {
    return "red";
  }
  if (value.includes("draft") || value.includes("pending") || value.includes("open") || value.includes("sent")) {
    return "amber";
  }
  return "blue";
}
async function buildPreview(kind, entityId, record) {
  const { t } = await resolveTranslations();
  const defaultTitle = kind === "quote" ? t("sales.messageObjects.quote.title") : t("sales.messageObjects.order.title");
  if (!record) {
    return {
      title: defaultTitle,
      subtitle: entityId,
      status: t("sales.messageObjects.notFound"),
      statusColor: "gray"
    };
  }
  const number = kind === "quote" ? record.quoteNumber : record.orderNumber;
  const customerName = resolveCustomerName(record.customerSnapshot ?? null);
  const total = formatTotal(record.grandTotalGrossAmount, record.currencyCode);
  const subtitleParts = [customerName, total].filter((part) => Boolean(part && part.trim().length > 0));
  const subtitle = subtitleParts.length > 0 ? subtitleParts.join(" \u2022 ") : entityId;
  const metadata = {};
  const numberLabel = t("sales.documents.detail.number");
  const customerLabel = t("sales.documents.detail.customer");
  const totalLabel = t("sales.documents.detail.totals.grandTotalGross");
  if (number) metadata[numberLabel] = number;
  if (customerName) metadata[customerLabel] = customerName;
  if (total) metadata[totalLabel] = total;
  return {
    title: number && number.trim().length > 0 ? number : defaultTitle,
    subtitle,
    status: record.status ?? void 0,
    statusColor: statusColor(record.status),
    metadata: Object.keys(metadata).length > 0 ? metadata : void 0
  };
}
async function loadDocumentRecord(kind, entityId, ctx) {
  if (!ctx.organizationId) return null;
  const { resolve } = await createRequestContainer();
  const em = resolve("em");
  const scope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId };
  if (kind === "quote") {
    return await findOneWithDecryption(
      em,
      SalesQuote,
      {
        id: entityId,
        tenantId: ctx.tenantId,
        organizationId: ctx.organizationId,
        deletedAt: null
      },
      void 0,
      scope
    );
  }
  return await findOneWithDecryption(
    em,
    SalesOrder,
    {
      id: entityId,
      tenantId: ctx.tenantId,
      organizationId: ctx.organizationId,
      deletedAt: null
    },
    void 0,
    scope
  );
}
async function loadSalesQuotePreview(entityId, ctx) {
  const record = await loadDocumentRecord("quote", entityId, ctx);
  return await buildPreview("quote", entityId, record);
}
async function loadSalesOrderPreview(entityId, ctx) {
  const record = await loadDocumentRecord("order", entityId, ctx);
  return await buildPreview("order", entityId, record);
}
async function loadSalesChannelPreview(entityId, ctx) {
  const { t } = await resolveTranslations();
  const defaultTitle = t("sales.messageObjects.channel.title");
  if (!ctx.organizationId) {
    return { title: defaultTitle, subtitle: entityId };
  }
  const { resolve } = await createRequestContainer();
  const em = resolve("em");
  const entity = await findOneWithDecryption(
    em,
    SalesChannel,
    {
      id: entityId,
      tenantId: ctx.tenantId,
      organizationId: ctx.organizationId,
      deletedAt: null
    },
    void 0,
    { tenantId: ctx.tenantId, organizationId: ctx.organizationId }
  );
  if (!entity) {
    return {
      title: defaultTitle,
      subtitle: entityId,
      status: t("sales.messageObjects.notFound"),
      statusColor: "gray"
    };
  }
  const metadata = {};
  const contactEmailLabel = t("sales.channels.form.contactEmail");
  const websiteUrlLabel = t("sales.channels.form.websiteUrl");
  if (entity.contactEmail && entity.contactEmail.trim().length > 0) metadata[contactEmailLabel] = entity.contactEmail;
  if (entity.websiteUrl && entity.websiteUrl.trim().length > 0) metadata[websiteUrlLabel] = entity.websiteUrl;
  return {
    title: entity.name,
    subtitle: entity.status ?? void 0,
    status: entity.status ?? void 0,
    statusColor: statusColor(entity.status),
    metadata: Object.keys(metadata).length > 0 ? metadata : void 0
  };
}
export {
  loadSalesChannelPreview,
  loadSalesOrderPreview,
  loadSalesQuotePreview
};
//# sourceMappingURL=messageObjectPreviews.js.map
