import { NextResponse } from "next/server";
import { z } from "zod";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
import { resolveOrganizationScopeFilter } from "@open-mercato/core/modules/directory/utils/organizationScopeFilter";
import { WorkflowEvent, WorkflowInstance } from "../../../data/entities.js";
import { workflowEventDetailSchema } from "../../openapi.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows");
const metadata = {
  requireAuth: true,
  requireFeatures: ["workflows.instances.view"]
};
async function GET(request, context) {
  try {
    const params = await context.params;
    const container = await createRequestContainer();
    const em = container.resolve("em");
    const auth = await getAuthFromRequest(request);
    if (!auth) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    const scope = await resolveOrganizationScopeForRequest({ container, auth, request });
    const tenantId = auth.tenantId;
    const orgFilter = resolveOrganizationScopeFilter(scope, auth);
    if (!tenantId) {
      return NextResponse.json(
        { error: "Missing tenant context" },
        { status: 400 }
      );
    }
    const rbacService = container.resolve("rbacService");
    const hasPermission = await rbacService.userHasAllFeatures(
      auth.sub,
      ["workflows.instances.view"],
      { tenantId, organizationId: orgFilter.rbacOrganizationId }
    );
    if (!hasPermission) {
      return NextResponse.json(
        { error: "Insufficient permissions" },
        { status: 403 }
      );
    }
    const event = await em.findOne(WorkflowEvent, {
      id: params.id,
      tenantId,
      ...orgFilter.where
    });
    if (!event) {
      return NextResponse.json(
        { error: "Workflow event not found" },
        { status: 404 }
      );
    }
    const instance = await em.findOne(WorkflowInstance, {
      id: event.workflowInstanceId,
      tenantId,
      ...orgFilter.where
    });
    const response = {
      id: event.id,
      workflowInstanceId: event.workflowInstanceId,
      stepInstanceId: event.stepInstanceId,
      eventType: event.eventType,
      eventData: event.eventData,
      occurredAt: event.occurredAt.toISOString(),
      userId: event.userId,
      tenantId: event.tenantId,
      organizationId: event.organizationId,
      workflowInstance: instance ? {
        id: instance.id,
        workflowId: instance.workflowId,
        version: instance.version,
        status: instance.status,
        currentStepId: instance.currentStepId,
        correlationKey: instance.correlationKey,
        startedAt: instance.startedAt?.toISOString() || null,
        completedAt: instance.completedAt?.toISOString() || null,
        context: instance.context
      } : null
    };
    return NextResponse.json(response);
  } catch (error) {
    logger.error("Error getting workflow event", { err: error });
    return NextResponse.json(
      { error: "Failed to get workflow event" },
      { status: 500 }
    );
  }
}
const openApi = {
  methods: {
    GET: {
      summary: "Get workflow event by ID",
      description: "Get detailed information about a specific workflow event",
      tags: ["Workflows"],
      params: z.object({
        id: z.string()
      }),
      responses: [
        {
          status: 200,
          description: "Workflow event details",
          schema: workflowEventDetailSchema
        },
        {
          status: 401,
          description: "Unauthorized",
          schema: z.object({ error: z.string() })
        },
        {
          status: 403,
          description: "Insufficient permissions",
          schema: z.object({ error: z.string() })
        },
        {
          status: 404,
          description: "Workflow event not found",
          schema: z.object({ error: z.string() })
        },
        {
          status: 500,
          description: "Internal server error",
          schema: z.object({ error: z.string() })
        }
      ]
    }
  }
};
export {
  GET,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
