import { NextResponse } from "next/server";
import { z } from "zod";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { getBundle, getBundleIntegrations, getIntegration } from "@open-mercato/shared/modules/integrations/types";
import { CredentialsEncryptionUnavailableError } from "../../lib/credentials-service.js";
import { deriveIntegrationHealthStatus, getEffectiveHealthCheckConfig } from "../../lib/health-service.js";
import {
  finalizeIntegrationsReadResponse,
  integrationApiRoutePaths,
  runIntegrationsReadBeforeInterceptors
} from "../umes-read.js";
const idParamsSchema = z.object({ id: z.string().min(1) });
const metadata = {
  GET: { requireAuth: true, requireFeatures: ["integrations.view"] }
};
const openApi = {
  tags: ["Integrations"],
  summary: "Get integration detail"
};
async function GET(req, ctx) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.tenantId || !auth.orgId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const rawParams = ctx.params && typeof ctx.params.then === "function" ? await ctx.params : ctx.params;
  const parsedParams = idParamsSchema.safeParse(rawParams);
  if (!parsedParams.success) {
    return NextResponse.json({ error: "Invalid integration id" }, { status: 400 });
  }
  const integration = getIntegration(parsedParams.data.id);
  if (!integration) {
    return NextResponse.json({ error: "Integration not found" }, { status: 404 });
  }
  const container = await createRequestContainer();
  const beforeInterceptors = await runIntegrationsReadBeforeInterceptors({
    routePath: integrationApiRoutePaths.detail,
    request: req,
    auth,
    container
  });
  if (!beforeInterceptors.ok) {
    return NextResponse.json(beforeInterceptors.body, { status: beforeInterceptors.statusCode });
  }
  const credentialsService = container.resolve("integrationCredentialsService");
  const stateService = container.resolve("integrationStateService");
  const logService = container.resolve("integrationLogService");
  const scope = { organizationId: auth.orgId, tenantId: auth.tenantId };
  const [credentials, credentialsUpdatedAt, state, analyticsMap] = await Promise.all([
    credentialsService.resolve(integration.id, scope).catch((err) => {
      if (err instanceof CredentialsEncryptionUnavailableError) return null;
      throw err;
    }),
    credentialsService.resolveUpdatedAt(integration.id, scope).catch((err) => {
      if (err instanceof CredentialsEncryptionUnavailableError) return null;
      throw err;
    }),
    stateService.resolveState(integration.id, scope),
    logService.aggregateAnalytics([integration.id], scope, 30)
  ]);
  const hasCredentials = credentials != null && Object.keys(credentials).length > 0;
  const healthConfig = getEffectiveHealthCheckConfig(integration.id);
  const hasHealthCheck = Boolean(healthConfig?.service);
  const healthStatus = deriveIntegrationHealthStatus({
    hasHealthCheck,
    hasCredentials,
    lastHealthStatus: state.lastHealthStatus,
    lastHealthCheckedAt: state.lastHealthCheckedAt
  });
  const analytics = analyticsMap.get(integration.id) ?? {
    lastActivityAt: null,
    totalCount: 0,
    errorCount: 0,
    errorRate: 0,
    dailyCounts: Array.from({ length: 30 }, () => 0)
  };
  const bundle = integration.bundleId ? getBundle(integration.bundleId) : void 0;
  const bundleIntegrations = integration.bundleId ? await Promise.all(
    getBundleIntegrations(integration.bundleId).map(async (item) => {
      const resolvedState = await stateService.resolveState(item.id, scope);
      return {
        ...item,
        isEnabled: resolvedState.isEnabled,
        state: {
          isEnabled: resolvedState.isEnabled,
          apiVersion: resolvedState.apiVersion,
          reauthRequired: resolvedState.reauthRequired,
          lastHealthStatus: resolvedState.lastHealthStatus,
          lastHealthCheckedAt: resolvedState.lastHealthCheckedAt?.toISOString() ?? null,
          lastHealthLatencyMs: resolvedState.lastHealthLatencyMs,
          enabledAt: resolvedState.enabledAt?.toISOString() ?? null,
          updatedAt: resolvedState.updatedAt?.toISOString() ?? null
        }
      };
    })
  ) : [];
  return finalizeIntegrationsReadResponse({
    routePath: integrationApiRoutePaths.detail,
    request: req,
    auth,
    container,
    interceptorRequest: beforeInterceptors.request,
    beforeMetadata: beforeInterceptors.metadataByInterceptor,
    enrich: {
      targetEntity: "integrations.integration",
      recordKeys: ["integration"],
      listKeys: ["bundleIntegrations"]
    },
    body: {
      integration,
      bundle,
      bundleIntegrations,
      state: {
        isEnabled: state.isEnabled,
        apiVersion: state.apiVersion,
        reauthRequired: state.reauthRequired,
        lastHealthStatus: state.lastHealthStatus,
        lastHealthCheckedAt: state.lastHealthCheckedAt?.toISOString() ?? null,
        lastHealthLatencyMs: state.lastHealthLatencyMs,
        enabledAt: state.enabledAt?.toISOString() ?? null,
        updatedAt: state.updatedAt?.toISOString() ?? null
      },
      hasCredentials,
      credentialsUpdatedAt: credentialsUpdatedAt?.toISOString() ?? null,
      healthStatus,
      analytics
    }
  });
}
export {
  GET,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
