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 * as startValidator from "../../../lib/start-validator.js";
import {
  workflowsTag,
  validateStartRequestSchema,
  validateStartResponseSchema,
  workflowErrorSchema
} from "../../openapi.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows");
const metadata = {
  requireAuth: true,
  requireFeatures: ["workflows.instances.view"]
};
const validateStartInputSchema = z.object({
  workflowId: z.string().min(1),
  version: z.number().int().positive().optional(),
  context: z.record(z.string(), z.any()).optional().default({}),
  locale: z.string().default("en")
});
async function POST(request) {
  try {
    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;
    if (!tenantId || !organizationId) {
      return NextResponse.json(
        { error: "Missing tenant or organization context" },
        { status: 400 }
      );
    }
    const body = await request.json();
    const validation = validateStartInputSchema.safeParse(body);
    if (!validation.success) {
      return NextResponse.json(
        { error: "Validation failed", details: validation.error.issues },
        { status: 400 }
      );
    }
    const { workflowId, version, context, locale } = validation.data;
    const result = await startValidator.validateWorkflowStart(em, {
      workflowId,
      version,
      context,
      locale,
      tenantId,
      organizationId
    });
    return NextResponse.json({
      canStart: result.canStart,
      workflowId,
      errors: result.errors.length > 0 ? result.errors : void 0,
      validatedRules: result.validatedRules.length > 0 ? result.validatedRules : void 0
    });
  } catch (error) {
    logger.error("Error validating workflow start", { err: error });
    return NextResponse.json(
      { error: "Failed to validate workflow start" },
      { status: 500 }
    );
  }
}
const openApi = {
  tag: workflowsTag,
  summary: "Validate workflow start",
  methods: {
    POST: {
      summary: "Validate if workflow can be started",
      description: "Evaluates pre-conditions defined on the START step and returns validation errors with localized messages if any fail. Returns canStart: true/false with details.",
      requestBody: {
        contentType: "application/json",
        schema: validateStartRequestSchema
      },
      responses: [
        { status: 200, description: "Validation result (canStart, errors, validatedRules)", schema: validateStartResponseSchema }
      ],
      errors: [
        { status: 400, description: "Invalid request body or missing context", schema: workflowErrorSchema },
        { status: 401, description: "Unauthorized", schema: workflowErrorSchema },
        { status: 500, description: "Internal server error", schema: workflowErrorSchema }
      ]
    }
  }
};
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
