import { NextResponse } from "next/server";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
import {
  createWidgetDataService,
  WidgetDataValidationError
} from "../../../services/widgetDataService.js";
import { runApiInterceptorsBefore } from "@open-mercato/shared/lib/crud/interceptor-runner";
import { dashboardsTag, dashboardsErrorSchema } from "../../openapi.js";
import { widgetDataRequestSchema, widgetDataResponseSchema } from "./schema.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("dashboards").child({ component: "widgets-data" });
const metadata = {
  POST: { requireAuth: true, requireFeatures: ["analytics.view"] }
};
async function POST(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  let body;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }
  const parsed = widgetDataRequestSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { error: "Invalid request payload", issues: parsed.error.issues },
      { status: 400 }
    );
  }
  const container = await createRequestContainer();
  const analyticsRegistry = container.resolve("analyticsRegistry");
  const entityFeatures = analyticsRegistry.getRequiredFeatures(parsed.data.entityType);
  if (entityFeatures && entityFeatures.length > 0) {
    const rbacService = container.resolve("rbacService");
    const hasAccess = await rbacService.userHasAllFeatures(auth.sub, entityFeatures, {
      tenantId: auth.tenantId,
      organizationId: auth.orgId
    });
    if (!hasAccess) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }
  }
  const em = container.resolve("em").fork({
    clear: true,
    freshEventManager: true,
    useContext: true
  });
  const tenantId = auth.tenantId ?? null;
  if (!tenantId) {
    return NextResponse.json({ error: "Tenant context is required" }, { status: 400 });
  }
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
  const organizationIds = (() => {
    if (scope?.selectedId) return [scope.selectedId];
    if (Array.isArray(scope?.filterIds) && scope.filterIds.length > 0) return scope.filterIds;
    if (scope?.allowedIds === null) return void 0;
    if (auth.orgId) return [auth.orgId];
    return void 0;
  })();
  const userFeatures = Array.isArray(auth.features) ? auth.features.filter((value) => typeof value === "string") : [];
  const headers = {};
  req.headers.forEach((value, key) => {
    headers[key] = value;
  });
  const interceptorResult = await runApiInterceptorsBefore({
    routePath: "dashboards/widgets/data",
    method: "POST",
    request: {
      method: "POST",
      url: req.url,
      headers,
      body: parsed.data
    },
    context: {
      em,
      container,
      userId: auth.sub ?? "",
      tenantId,
      organizationId: organizationIds?.[0] ?? auth.orgId ?? "",
      userFeatures
    }
  });
  if (!interceptorResult.ok) {
    return NextResponse.json(interceptorResult.body, { status: interceptorResult.statusCode });
  }
  const requestData = interceptorResult.request.body ?? parsed.data;
  try {
    const cache = container.resolve("cache");
    const service = createWidgetDataService(em, { tenantId, organizationIds }, analyticsRegistry, cache);
    const result = await service.fetchWidgetData(requestData);
    return NextResponse.json(result);
  } catch (err) {
    logger.error("Widget data request failed", { err });
    if (err instanceof WidgetDataValidationError) {
      return NextResponse.json({ error: err.message }, { status: 400 });
    }
    return NextResponse.json(
      { error: "An error occurred while processing your request" },
      { status: 500 }
    );
  }
}
const widgetDataPostDoc = {
  summary: "Fetch aggregated data for dashboard widgets",
  description: "Executes an aggregation query against the specified entity type and returns the result. Supports date range filtering, grouping, and period-over-period comparison.",
  tags: [dashboardsTag],
  requestBody: {
    contentType: "application/json",
    schema: widgetDataRequestSchema,
    description: "Widget data request configuration specifying entity type, metric, filters, and grouping."
  },
  responses: [
    {
      status: 200,
      description: "Aggregated data for the widget.",
      schema: widgetDataResponseSchema
    }
  ],
  errors: [
    { status: 400, description: "Invalid request payload", schema: dashboardsErrorSchema },
    { status: 401, description: "Authentication required", schema: dashboardsErrorSchema },
    { status: 403, description: "Missing analytics.view feature", schema: dashboardsErrorSchema },
    { status: 500, description: "Internal server error", schema: dashboardsErrorSchema }
  ]
};
const openApi = {
  tag: dashboardsTag,
  summary: "Widget data aggregation endpoint",
  methods: {
    POST: widgetDataPostDoc
  }
};
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
