import { sql } from "kysely";
import { parseBooleanFromUnknown } from "@open-mercato/shared/lib/boolean";
async function attachResourceTypeCounts(payload, ctx) {
  if (!parseBooleanFromUnknown(ctx.query?.withResourceCounts)) return;
  const items = Array.isArray(payload?.items) ? payload.items : [];
  if (!items.length) return;
  const typeIds = items.map((item) => typeof item.id === "string" ? item.id : null).filter((id) => typeof id === "string" && id.length > 0);
  if (!typeIds.length) return;
  const tenantId = ctx.organizationScope?.tenantId ?? ctx.auth?.tenantId ?? null;
  const orgIds = ctx.organizationIds ?? ctx.organizationScope?.filterIds ?? null;
  const singleOrgId = ctx.selectedOrganizationId ?? ctx.organizationScope?.selectedId ?? null;
  const db = ctx.container.resolve("em").getKysely();
  let query = db.selectFrom("resources_resources").select(["resource_type_id", sql`count(*)`.as("count")]).where("resource_type_id", "in", typeIds).where("deleted_at", "is", null);
  if (tenantId) query = query.where("tenant_id", "=", tenantId);
  if (Array.isArray(orgIds) && orgIds.length > 0) {
    query = query.where("organization_id", "in", orgIds);
  } else if (singleOrgId) {
    query = query.where("organization_id", "=", singleOrgId);
  }
  const rows = await query.groupBy("resource_type_id").execute();
  const countMap = /* @__PURE__ */ new Map();
  for (const row of rows) {
    if (typeof row.resource_type_id !== "string") continue;
    const count = typeof row.count === "string" ? Number.parseInt(row.count, 10) : Number(row.count);
    countMap.set(row.resource_type_id, Number.isFinite(count) ? count : 0);
  }
  for (const item of items) {
    if (typeof item.id !== "string") continue;
    item.resourceCount = countMap.get(item.id) ?? 0;
  }
}
export {
  attachResourceTypeCounts
};
//# sourceMappingURL=resourceTypeCounts.js.map
