import { getEntityIds } from "@open-mercato/shared/lib/encryption/entityIds";
import { getModules } from "@open-mercato/shared/lib/i18n/server";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("attachments");
let _entityLinkSpecsCache = null;
function getEntityLinkSpecs() {
  if (_entityLinkSpecsCache) return _entityLinkSpecsCache;
  const E = getEntityIds();
  const specs = {};
  if (E.catalog?.catalog_product) {
    specs[E.catalog.catalog_product] = {
      labelFields: ["title", "sku", "handle"],
      buildHref: (record) => buildSimpleHref("/backend/catalog/products", record.id)
    };
  }
  if (E.catalog?.catalog_product_variant) {
    specs[E.catalog.catalog_product_variant] = {
      labelFields: ["name", "sku"],
      extraFields: ["product_id"],
      buildHref: (record) => {
        const productId = readRecordValue(record, "product_id");
        if (!productId) return null;
        return `/backend/catalog/products/${encodeURIComponent(productId)}/variants/${encodeURIComponent(String(record.id ?? ""))}`;
      }
    };
  }
  if (E.customers?.customer_entity) {
    specs[E.customers.customer_entity] = {
      labelFields: ["display_name"],
      extraFields: ["kind"],
      buildHref: (record) => {
        const kind = String(readRecordValue(record, "kind") || "").toLowerCase();
        if (kind === "company") return buildSimpleHref("/backend/customers/companies", record.id);
        if (kind === "person") return buildSimpleHref("/backend/customers/people", record.id);
        return null;
      }
    };
  }
  if (E.customers?.customer_person_profile) {
    specs[E.customers.customer_person_profile] = {
      labelFields: ["preferred_name", "display_name", "first_name", "last_name"],
      extraFields: ["entity_id", "first_name", "last_name"],
      buildHref: (record) => {
        const entityId = readRecordValue(record, "entity_id");
        return entityId ? buildSimpleHref("/backend/customers/people", entityId) : null;
      }
    };
  }
  if (E.customers?.customer_company_profile) {
    specs[E.customers.customer_company_profile] = {
      labelFields: ["brand_name", "display_name", "legal_name"],
      extraFields: ["entity_id"],
      buildHref: (record) => {
        const entityId = readRecordValue(record, "entity_id");
        return entityId ? buildSimpleHref("/backend/customers/companies", entityId) : null;
      }
    };
  }
  if (E.customers?.customer_deal) {
    specs[E.customers.customer_deal] = {
      labelFields: ["title"],
      buildHref: (record) => buildSimpleHref("/backend/customers/deals", record.id)
    };
  }
  if (E.sales?.sales_channel) {
    specs[E.sales.sales_channel] = {
      labelFields: ["name", "title"],
      buildHref: (record) => buildSimpleHref("/backend/sales/channels", record.id, "/edit")
    };
  }
  _entityLinkSpecsCache = specs;
  return _entityLinkSpecsCache;
}
const LIBRARY_ENTITY_ID = "attachments:library";
const DEFAULT_LABEL_FIELDS = [
  "label",
  "title",
  "name",
  "display_name",
  "displayName",
  "subject",
  "sku",
  "handle",
  "order_number",
  "quote_number",
  "invoice_number",
  "email",
  "company_name",
  "legal_name",
  "brand_name"
];
let entitySpecsPromise = null;
async function loadEntitySpecs() {
  if (!entitySpecsPromise) {
    entitySpecsPromise = Promise.resolve().then(() => {
      const map = /* @__PURE__ */ new Map();
      const mods = getModules();
      for (const mod of mods) {
        const specs = mod.customEntities ?? [];
        for (const spec of specs) {
          if (spec?.id && !map.has(spec.id)) {
            map.set(spec.id, spec);
          }
        }
      }
      return map;
    }).catch(() => /* @__PURE__ */ new Map());
  }
  return entitySpecsPromise;
}
function camelToSnake(value) {
  return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[\s-]+/g, "_").toLowerCase();
}
function snakeToCamel(value) {
  return value.replace(/[_-](\w)/g, (_, c) => c.toUpperCase());
}
function normalizeValue(value) {
  if (value === void 0 || value === null) return null;
  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed.length ? trimmed : null;
  }
  if (typeof value === "number" || typeof value === "boolean") {
    return String(value);
  }
  return null;
}
function readRecordValue(record, field) {
  if (!field) return null;
  if (record[field] !== void 0) return normalizeValue(record[field]);
  const snake = camelToSnake(field);
  if (snake !== field && record[snake] !== void 0) return normalizeValue(record[snake]);
  const camel = snakeToCamel(field);
  if (camel !== field && record[camel] !== void 0) return normalizeValue(record[camel]);
  return null;
}
function buildSimpleHref(base, idValue, suffix = "") {
  const id = normalizeValue(idValue);
  if (!id) return null;
  return `${base}/${encodeURIComponent(id)}${suffix}`;
}
function isUuid(value) {
  return typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.trim());
}
function filterIdsForEntity(entityId, ids) {
  const E = getEntityIds();
  if (entityId === E.catalog?.catalog_product_variant || entityId === E.catalog?.catalog_product) {
    return ids.filter((id) => isUuid(id));
  }
  return ids;
}
function resolveLabelCandidates(entityId, linkSpec, entitySpecs) {
  const candidates = /* @__PURE__ */ new Set();
  const spec = entitySpecs.get(entityId);
  if (spec?.labelField) {
    candidates.add(spec.labelField);
    candidates.add(camelToSnake(spec.labelField));
  }
  for (const field of linkSpec?.labelFields ?? []) {
    candidates.add(field);
    candidates.add(camelToSnake(field));
  }
  DEFAULT_LABEL_FIELDS.forEach((field) => {
    candidates.add(field);
    candidates.add(camelToSnake(field));
  });
  return Array.from(candidates).filter((field) => field.length > 0);
}
function buildLabel(record, entityId, linkSpec, entitySpecs) {
  const candidates = resolveLabelCandidates(entityId, linkSpec, entitySpecs);
  for (const candidate of candidates) {
    const value = readRecordValue(record, candidate);
    if (value) return value;
  }
  const fullName = [readRecordValue(record, "first_name"), readRecordValue(record, "last_name")].filter((part) => Boolean(part)).join(" ").trim();
  if (fullName.length) return fullName;
  return null;
}
async function resolveAssignmentEnrichments(assignments, opts) {
  const map = /* @__PURE__ */ new Map();
  if (!assignments.length || !opts.queryEngine) return map;
  const entitySpecs = await loadEntitySpecs();
  const grouped = /* @__PURE__ */ new Map();
  for (const assignment of assignments) {
    if (!assignment || assignment.type === LIBRARY_ENTITY_ID) continue;
    const type = assignment.type?.trim();
    const id = assignment.id?.trim();
    if (!type || !id) continue;
    if (!grouped.has(type)) grouped.set(type, /* @__PURE__ */ new Set());
    grouped.get(type).add(id);
  }
  if (!grouped.size) return map;
  const entityLinkSpecs = getEntityLinkSpecs();
  for (const [entityId, idsSet] of grouped.entries()) {
    const ids = filterIdsForEntity(entityId, Array.from(idsSet.values()));
    if (!ids.length) continue;
    const linkSpec = entityLinkSpecs[entityId];
    const fields = /* @__PURE__ */ new Set(["id"]);
    const candidates = resolveLabelCandidates(entityId, linkSpec, entitySpecs);
    candidates.forEach((field) => fields.add(field));
    for (const extra of linkSpec?.extraFields ?? []) {
      fields.add(extra);
      fields.add(camelToSnake(extra));
    }
    try {
      const result = await opts.queryEngine.query(entityId, {
        fields: Array.from(fields),
        filters: { id: ids.length === 1 ? { $eq: ids[0] } : { $in: ids } },
        tenantId: opts.tenantId,
        organizationId: opts.organizationId ?? void 0,
        page: { pageSize: Math.max(ids.length, 20) }
      });
      for (const record of result.items ?? []) {
        const recordId = normalizeValue(record.id);
        if (!recordId) continue;
        const label = buildLabel(record, entityId, linkSpec, entitySpecs);
        const href = linkSpec?.buildHref?.(record) ?? null;
        if (label || href) {
          map.set(`${entityId}:${recordId}`, {
            label: label ?? void 0,
            href: href ?? void 0
          });
        }
      }
    } catch (error) {
      logger.warn("Failed to resolve assignment details", { entityId, err: error });
    }
  }
  return map;
}
function applyAssignmentEnrichments(assignments, enrichments) {
  if (!enrichments.size) return assignments;
  return assignments.map((assignment) => {
    if (!assignment || !assignment.type || !assignment.id) return assignment;
    const key = `${assignment.type}:${assignment.id}`;
    const detail = enrichments.get(key);
    if (!detail) return assignment;
    const next = { ...assignment };
    if (!next.label && detail.label) next.label = detail.label;
    if (!next.href && detail.href) next.href = detail.href;
    return next;
  });
}
export {
  applyAssignmentEnrichments,
  resolveAssignmentEnrichments
};
//# sourceMappingURL=assignmentDetails.js.map
