import { QueryOrder } from "@mikro-orm/postgresql";
import { FeatureToggle, FeatureToggleOverride } from "../data/entities.js";
import { escapeLikePattern } from "@open-mercato/shared/lib/db/escapeLikePattern";
const SORTABLE_FIELDS = /* @__PURE__ */ new Set(["identifier", "name", "category"]);
async function getOverrides(em, tenant, query) {
  const filters = { deletedAt: null };
  if (query.category) {
    filters.category = { $ilike: `%${escapeLikePattern(query.category)}%` };
  }
  if (query.name) {
    filters.name = { $ilike: `%${escapeLikePattern(query.name)}%` };
  }
  if (query.identifier) {
    filters.identifier = { $ilike: `%${escapeLikePattern(query.identifier)}%` };
  }
  const page = query.page ?? 1;
  const pageSize = query.pageSize ?? 25;
  const offset = (page - 1) * pageSize;
  const direction = query.sortDir === "desc" ? QueryOrder.DESC : QueryOrder.ASC;
  const orderBy = {};
  if (query.sortField && SORTABLE_FIELDS.has(query.sortField)) {
    orderBy[query.sortField] = direction;
  }
  orderBy.id = QueryOrder.ASC;
  const totalItems = await em.count(FeatureToggle, filters);
  const globalToggles = await em.find(FeatureToggle, filters, {
    orderBy,
    limit: pageSize,
    offset
  });
  const overrides = globalToggles.length ? await em.find(FeatureToggleOverride, {
    tenantId: tenant.id,
    toggle: { id: { $in: globalToggles.map((toggle) => toggle.id) } }
  }) : [];
  const overridesByToggleId = /* @__PURE__ */ new Map();
  for (const override of overrides) {
    overridesByToggleId.set(override.toggle.id, override);
  }
  const items = globalToggles.map((toggle) => {
    const override = overridesByToggleId.get(toggle.id);
    return {
      id: override?.id ?? "",
      toggleId: toggle.id,
      tenantName: tenant.name,
      tenantId: tenant.id,
      identifier: toggle.identifier,
      name: toggle.name,
      category: toggle.category ?? "",
      isOverride: Boolean(override),
      updatedAt: override?.updatedAt instanceof Date ? override.updatedAt.toISOString() : null
    };
  });
  const totalPages = Math.ceil(totalItems / pageSize);
  return {
    items,
    total: totalItems,
    totalPages,
    page,
    pageSize,
    raw: {
      toggles: globalToggles,
      overrides
    }
  };
}
export {
  getOverrides
};
//# sourceMappingURL=queries.js.map
