import { NextResponse } from "next/server";
import { runApiInterceptorsAfter, runApiInterceptorsBefore } from "@open-mercato/shared/lib/crud/interceptor-runner";
import { applyResponseEnrichers, applyResponseEnricherToRecord } from "@open-mercato/shared/lib/crud/enricher-runner";
const integrationApiRoutePaths = {
  list: "integrations",
  detail: "integrations/detail",
  logs: "integrations/logs"
};
function headersToObject(headers) {
  return Object.fromEntries(headers.entries());
}
function searchParamsToObject(url) {
  const entries = {};
  url.searchParams.forEach((value, key) => {
    entries[key] = value;
  });
  return entries;
}
function toUserFeatures(features) {
  if (!Array.isArray(features)) return [];
  return features.filter((value) => typeof value === "string");
}
function mergeAdditiveRecord(base, candidate) {
  const additions = Object.fromEntries(
    Object.entries(candidate).filter(([key]) => !(key in base))
  );
  return {
    ...base,
    ...additions
  };
}
function mergeAdditiveBody(baseBody, candidateBody) {
  return mergeAdditiveRecord(baseBody, candidateBody);
}
function getEnricherContext(input) {
  return {
    organizationId: input.auth.orgId,
    tenantId: input.auth.tenantId,
    userId: input.auth.sub ?? "",
    em: input.container.resolve("em"),
    container: input.container,
    userFeatures: toUserFeatures(input.auth.features)
  };
}
async function runIntegrationsReadBeforeInterceptors(input) {
  const url = new URL(input.request.url);
  return runApiInterceptorsBefore({
    routePath: input.routePath,
    method: "GET",
    request: {
      method: "GET",
      url: input.request.url,
      headers: headersToObject(input.request.headers),
      query: searchParamsToObject(url)
    },
    context: getEnricherContext(input)
  });
}
async function applySafeRecordEnrichment(record, targetEntity, context) {
  const enriched = await applyResponseEnricherToRecord(record, targetEntity, context);
  return mergeAdditiveRecord(record, enriched.record);
}
async function applySafeListEnrichment(items, targetEntity, context) {
  const enriched = await applyResponseEnrichers(items, targetEntity, context);
  return items.map((item, index) => {
    const enrichedItem = enriched.items[index];
    if (!enrichedItem) return item;
    return mergeAdditiveRecord(item, enrichedItem);
  });
}
async function finalizeIntegrationsReadResponse(input) {
  const method = input.method ?? "GET";
  const baseBody = input.body;
  const context = getEnricherContext(input);
  const intercepted = await runApiInterceptorsAfter({
    routePath: input.routePath,
    method,
    request: input.interceptorRequest,
    response: {
      statusCode: 200,
      body: baseBody,
      headers: {}
    },
    context,
    metadataByInterceptor: input.beforeMetadata
  });
  if (!intercepted.ok) {
    return NextResponse.json(intercepted.body, { status: intercepted.statusCode, headers: intercepted.headers });
  }
  let responseBody = mergeAdditiveBody(baseBody, intercepted.body);
  if (input.enrich) {
    const { targetEntity, recordKeys = [], listKeys = [] } = input.enrich;
    for (const key of recordKeys) {
      const current = responseBody[key];
      if (!current || typeof current !== "object" || Array.isArray(current)) continue;
      responseBody = {
        ...responseBody,
        [key]: await applySafeRecordEnrichment(current, targetEntity, context)
      };
    }
    for (const key of listKeys) {
      const current = responseBody[key];
      if (!Array.isArray(current)) continue;
      const records = current.filter(
        (item) => typeof item === "object" && item !== null && !Array.isArray(item)
      );
      if (records.length !== current.length) continue;
      responseBody = {
        ...responseBody,
        [key]: await applySafeListEnrichment(records, targetEntity, context)
      };
    }
  }
  return NextResponse.json(responseBody, { headers: intercepted.headers });
}
export {
  finalizeIntegrationsReadResponse,
  integrationApiRoutePaths,
  runIntegrationsReadBeforeInterceptors
};
//# sourceMappingURL=umes-read.js.map
