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 { serializeOperationMetadata } from "@open-mercato/shared/lib/commands/operationMetadata";
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { parseScopedCommandInput } from "@open-mercato/shared/lib/api/scoped";
import { staffLeaveRequestDecisionSchema } from "../../../data/validators.js";
import {
  resolveUserFeatures,
  runStaffMutationGuardAfterSuccess,
  runStaffMutationGuards
} from "../../guards.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("staff");
const metadata = {
  POST: { requireAuth: true, requireFeatures: ["staff.leave_requests.manage"] }
};
async function buildContext(req) {
  const container = await createRequestContainer();
  const auth = await getAuthFromRequest(req);
  const { translate } = await resolveTranslations();
  if (!auth) throw new CrudHttpError(401, { error: translate("staff.errors.unauthorized", "Unauthorized") });
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
  const ctx = {
    container,
    auth,
    organizationScope: scope,
    selectedOrganizationId: scope?.selectedId ?? auth.orgId ?? null,
    organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),
    request: req
  };
  return { ctx, translate };
}
async function POST(req) {
  try {
    const { ctx, translate } = await buildContext(req);
    const body = await req.json().catch(() => ({}));
    const input = parseScopedCommandInput(staffLeaveRequestDecisionSchema, body, ctx, translate);
    const auth = ctx.auth;
    const tenantId = auth?.tenantId ?? "";
    const organizationId = ctx.selectedOrganizationId ?? null;
    const guardResult = await runStaffMutationGuards(
      ctx.container,
      {
        tenantId,
        organizationId,
        userId: auth?.sub ?? "",
        resourceKind: "staff.leave_request",
        resourceId: input.id,
        operation: "update",
        requestMethod: req.method,
        requestHeaders: req.headers,
        mutationPayload: input
      },
      resolveUserFeatures(auth)
    );
    if (!guardResult.ok) {
      return NextResponse.json(
        guardResult.errorBody ?? { error: "Operation blocked by guard" },
        { status: guardResult.errorStatus ?? 422 }
      );
    }
    const commandBus = ctx.container.resolve("commandBus");
    const { result, logEntry } = await commandBus.execute(
      "staff.leave-requests.reject",
      { input, ctx }
    );
    if (guardResult.afterSuccessCallbacks.length) {
      await runStaffMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {
        tenantId,
        organizationId,
        userId: auth?.sub ?? "",
        resourceKind: "staff.leave_request",
        resourceId: result?.requestId ?? input.id,
        operation: "update",
        requestMethod: req.method,
        requestHeaders: req.headers
      });
    }
    const response = NextResponse.json({ ok: true, id: result?.requestId ?? null }, { status: 200 });
    if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {
      response.headers.set(
        "x-om-operation",
        serializeOperationMetadata({
          id: logEntry.id,
          undoToken: logEntry.undoToken,
          commandId: logEntry.commandId,
          actionLabel: logEntry.actionLabel ?? null,
          resourceKind: logEntry.resourceKind ?? "staff.leave_request",
          resourceId: logEntry.resourceId ?? result?.requestId ?? null,
          executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : void 0
        })
      );
    }
    return response;
  } catch (err) {
    if (isCrudHttpError(err)) {
      return NextResponse.json(err.body, { status: err.status });
    }
    const { translate } = await resolveTranslations();
    logger.error("staff.leave-requests.reject failed", { err });
    return NextResponse.json({ error: translate("staff.leaveRequests.errors.reject", "Failed to reject leave request.") }, { status: 400 });
  }
}
const openApi = {
  tag: "Staff",
  summary: "Reject leave request",
  methods: {
    POST: {
      summary: "Reject leave request",
      description: "Rejects a leave request with an optional comment.",
      requestBody: {
        contentType: "application/json",
        schema: staffLeaveRequestDecisionSchema
      },
      responses: [
        { status: 200, description: "Leave request rejected", schema: z.object({ ok: z.literal(true), id: z.string().uuid().nullable() }) },
        { status: 400, description: "Invalid payload", schema: z.object({ error: z.string() }) },
        { status: 401, description: "Unauthorized", schema: z.object({ error: z.string() }) },
        { status: 403, description: "Forbidden", schema: z.object({ error: z.string() }) }
      ]
    }
  }
};
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
