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 { validateCrudMutationGuard, runCrudMutationGuardAfterSuccess } from "@open-mercato/shared/lib/crud/mutation-guard";
import { WorkflowDefinition, WorkflowInstance } from "../../../../data/entities.js";
import { serializeCodeWorkflowDefinition } from "../../serialize.js";
import { getCodeWorkflow } from "../../../../lib/code-registry.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows");
const metadata = {
  requireAuth: true,
  requireFeatures: ["workflows.definitions.edit"]
};
async function POST(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 organizationId = scope?.selectedId ?? auth.orgId;
    const rbacService = container.resolve("rbacService");
    const hasPermission = await rbacService.userHasAllFeatures(
      auth.sub,
      ["workflows.definitions.edit"],
      {
        tenantId,
        organizationId
      }
    );
    if (!hasPermission) {
      return NextResponse.json(
        { error: "Insufficient permissions" },
        { status: 403 }
      );
    }
    const definition = await em.findOne(WorkflowDefinition, {
      id: params.id,
      tenantId,
      organizationId,
      deletedAt: null
    });
    if (!definition) {
      return NextResponse.json(
        { error: "Workflow definition not found" },
        { status: 404 }
      );
    }
    if (!definition.codeWorkflowId) {
      return NextResponse.json(
        { error: "This workflow definition is not a code-based override and cannot be reset" },
        { status: 400 }
      );
    }
    const activeInstances = await em.count(WorkflowInstance, {
      definitionId: definition.id,
      status: { $in: ["RUNNING", "WAITING"] }
    });
    if (activeInstances > 0) {
      return NextResponse.json(
        {
          error: `Cannot reset workflow definition with ${activeInstances} active instance(s)`
        },
        { status: 409 }
      );
    }
    const guardResult = await validateCrudMutationGuard(container, {
      tenantId: tenantId ?? "",
      organizationId: organizationId ?? null,
      userId: auth.sub ?? "",
      resourceKind: "workflows.definition",
      resourceId: String(definition.id),
      operation: "custom",
      requestMethod: "POST",
      requestHeaders: request.headers
    });
    if (guardResult && !guardResult.ok) {
      return NextResponse.json(guardResult.body, { status: guardResult.status });
    }
    const codeDef = getCodeWorkflow(definition.codeWorkflowId);
    const removedSnapshot = {
      id: String(definition.id),
      workflowId: definition.workflowId,
      codeWorkflowId: definition.codeWorkflowId,
      tenantId: definition.tenantId,
      organizationId: definition.organizationId
    };
    em.remove(definition);
    await em.flush();
    if (guardResult?.shouldRunAfterSuccess) {
      await runCrudMutationGuardAfterSuccess(container, {
        tenantId: tenantId ?? "",
        organizationId: organizationId ?? null,
        userId: auth.sub ?? "",
        resourceKind: "workflows.definition",
        resourceId: removedSnapshot.id,
        operation: "custom",
        requestMethod: "POST",
        requestHeaders: request.headers,
        metadata: guardResult.metadata
      });
    }
    try {
      const eventBus = container.resolve("eventBus");
      if (eventBus && typeof eventBus.emitEvent === "function") {
        await eventBus.emitEvent(
          "workflows.definition.reset_to_code",
          {
            id: removedSnapshot.id,
            workflowId: removedSnapshot.workflowId,
            codeWorkflowId: removedSnapshot.codeWorkflowId,
            tenantId: removedSnapshot.tenantId,
            organizationId: removedSnapshot.organizationId,
            userId: auth.sub ?? null
          },
          {
            tenantId: removedSnapshot.tenantId,
            organizationId: removedSnapshot.organizationId,
            persistent: true
          }
        );
      }
    } catch (eventError) {
      logger.error("Failed to emit workflows.definition.reset_to_code event", { err: eventError });
    }
    if (!codeDef) {
      return NextResponse.json({
        message: "Workflow definition reset to code version (code definition no longer registered)",
        data: null
      });
    }
    const syntheticId = `code:${codeDef.workflowId}`;
    return NextResponse.json({
      data: serializeCodeWorkflowDefinition(codeDef, syntheticId),
      message: "Workflow definition reset to code version"
    });
  } catch (error) {
    logger.error("Error resetting workflow definition to code", { err: error });
    return NextResponse.json(
      { error: "Failed to reset workflow definition to code" },
      { status: 500 }
    );
  }
}
const openApi = {
  methods: {
    POST: {
      summary: "Reset workflow definition to code version",
      description: "Deletes the DB override for a code-based workflow definition, reverting it to the original code registry version. Cannot be reset if there are active instances.",
      tags: ["Workflows"],
      pathParams: z.object({
        id: z.string().uuid()
      }),
      responses: [
        {
          status: 200,
          description: "Workflow definition reset to code version",
          example: {
            data: {
              id: "code:checkout-flow",
              workflowId: "checkout-flow",
              workflowName: "Checkout Flow",
              description: "Code-defined checkout workflow",
              version: 1,
              source: "code",
              isCodeBased: true
            },
            message: "Workflow definition reset to code version"
          }
        },
        {
          status: 400,
          description: "Definition is not a code-based override",
          example: {
            error: "This workflow definition is not a code-based override and cannot be reset"
          }
        },
        {
          status: 404,
          description: "Workflow definition not found",
          example: {
            error: "Workflow definition not found"
          }
        },
        {
          status: 409,
          description: "Cannot reset - active workflow instances exist",
          example: {
            error: "Cannot reset workflow definition with 3 active instance(s)"
          }
        }
      ]
    }
  }
};
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
