import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { CustomerUser, DomainMapping } from "./entities.js";
const PERSON_FALLBACK = { _customer_accounts: { hasAccount: false } };
const COMPANY_FALLBACK = { _customer_accounts: { userCount: 0 } };
const personAccountStatusEnricher = {
  id: "customer_accounts.person-account-status",
  targetEntity: "customers.person",
  features: ["customer_accounts.view"],
  priority: 10,
  timeout: 2e3,
  critical: false,
  fallback: PERSON_FALLBACK,
  async enrichOne(record, context) {
    return (await this.enrichMany([record], context))[0];
  },
  async enrichMany(records, context) {
    if (records.length === 0) return records;
    const em = context.em.fork();
    const recordIds = records.map((r) => r.id);
    const users = await findWithDecryption(
      em,
      CustomerUser,
      {
        personEntityId: { $in: recordIds },
        tenantId: context.tenantId,
        deletedAt: null
      },
      void 0,
      { tenantId: context.tenantId, organizationId: context.organizationId }
    );
    const userByPersonId = /* @__PURE__ */ new Map();
    for (const user of users) {
      if (user.personEntityId) {
        userByPersonId.set(user.personEntityId, user);
      }
    }
    return records.map((record) => {
      const user = userByPersonId.get(record.id);
      if (!user) {
        return { ...record, _customer_accounts: { hasAccount: false } };
      }
      return {
        ...record,
        _customer_accounts: {
          hasAccount: true,
          userId: user.id,
          isActive: user.isActive,
          lastLoginAt: user.lastLoginAt?.toISOString() ?? null
        }
      };
    });
  }
};
const companyUserCountEnricher = {
  id: "customer_accounts.company-user-count",
  targetEntity: "customers.company",
  features: ["customer_accounts.view"],
  priority: 10,
  timeout: 2e3,
  critical: false,
  fallback: COMPANY_FALLBACK,
  async enrichOne(record, context) {
    return (await this.enrichMany([record], context))[0];
  },
  async enrichMany(records, context) {
    if (records.length === 0) return records;
    const em = context.em.fork();
    const recordIds = records.map((r) => r.id);
    const users = await findWithDecryption(
      em,
      CustomerUser,
      {
        customerEntityId: { $in: recordIds },
        tenantId: context.tenantId,
        deletedAt: null
      },
      void 0,
      { tenantId: context.tenantId, organizationId: context.organizationId }
    );
    const countByCompanyId = /* @__PURE__ */ new Map();
    for (const user of users) {
      if (user.customerEntityId) {
        countByCompanyId.set(user.customerEntityId, (countByCompanyId.get(user.customerEntityId) ?? 0) + 1);
      }
    }
    return records.map((record) => ({
      ...record,
      _customer_accounts: {
        userCount: countByCompanyId.get(record.id) ?? 0
      }
    }));
  }
};
const ORG_DOMAIN_FALLBACK = { _customDomain: null };
const ACTIVE_DOMAIN_PRIORITY = {
  active: 0,
  verified: 1,
  pending: 2,
  tls_failed: 3,
  dns_failed: 4
};
function pickPrimaryDomain(records) {
  if (records.length === 0) return null;
  return records.slice().sort(
    (a, b) => (ACTIVE_DOMAIN_PRIORITY[a.status] ?? 99) - (ACTIVE_DOMAIN_PRIORITY[b.status] ?? 99) || (b.createdAt?.getTime?.() ?? 0) - (a.createdAt?.getTime?.() ?? 0)
  )[0];
}
const organizationCustomDomainEnricher = {
  id: "customer_accounts.domain-status:directory:organization",
  targetEntity: "directory:organization",
  features: ["customer_accounts.domain.manage"],
  priority: 10,
  timeout: 1e3,
  critical: false,
  fallback: ORG_DOMAIN_FALLBACK,
  async enrichOne(record, context) {
    return (await this.enrichMany([record], context))[0];
  },
  async enrichMany(records, context) {
    if (records.length === 0) return records;
    const em = context.em.fork();
    const recordIds = records.map((r) => r.id);
    const domains = await em.find(DomainMapping, {
      organizationId: { $in: recordIds },
      tenantId: context.tenantId
    });
    const byOrg = /* @__PURE__ */ new Map();
    for (const d of domains) {
      const list = byOrg.get(d.organizationId) ?? [];
      list.push(d);
      byOrg.set(d.organizationId, list);
    }
    return records.map((record) => {
      const matches = byOrg.get(record.id) ?? [];
      const primary = pickPrimaryDomain(matches);
      return {
        ...record,
        _customDomain: primary ? { hostname: primary.hostname, status: primary.status } : null
      };
    });
  }
};
const enrichers = [
  personAccountStatusEnricher,
  companyUserCountEnricher,
  organizationCustomDomainEnricher
];
export {
  enrichers
};
//# sourceMappingURL=enrichers.js.map
