import { NextResponse } from "next/server";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import {
  runCrudMutationGuardAfterSuccess,
  validateCrudMutationGuard
} from "@open-mercato/shared/lib/crud/mutation-guard";
import {
  CUSTOMERS_DEALS_BULK_UPDATE_STAGE_QUEUE,
  getCustomersQueue
} from "../../../lib/bulkDeals.js";
import {
  dealsBulkUpdateStageSchema as requestSchema,
  dealsBulkUpdateResponseSchema as responseSchema
} from "../../../data/validators.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
const metadata = {
  POST: { requireAuth: true, requireFeatures: ["customers.deals.manage"] }
};
const openApi = {
  tags: ["Customers"],
  summary: "Bulk update deal pipeline stage",
  description: "Queues a background job that moves the listed deals to the same pipeline stage. Returns a progress job id to poll for completion."
};
async function postImpl(req, translate) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.tenantId || !auth.orgId) {
    return NextResponse.json(
      responseSchema.parse({
        ok: false,
        progressJobId: null,
        message: translate("customers.errors.unauthorized", "Unauthorized")
      }),
      { status: 401 }
    );
  }
  const parsed = requestSchema.safeParse(await readJsonSafe(req));
  if (!parsed.success) {
    return NextResponse.json(
      responseSchema.parse({
        ok: false,
        progressJobId: null,
        message: translate("customers.errors.invalid_payload", "Invalid payload")
      }),
      { status: 400 }
    );
  }
  const ids = Array.from(new Set(parsed.data.ids));
  const container = await createRequestContainer();
  let guardResult = null;
  try {
    guardResult = await validateCrudMutationGuard(container, {
      tenantId: auth.tenantId,
      organizationId: auth.orgId,
      userId: auth.sub,
      resourceKind: "customers.deal",
      resourceId: ids.join(","),
      operation: "custom",
      requestMethod: req.method,
      requestHeaders: req.headers,
      mutationPayload: { ids, pipelineStageId: parsed.data.pipelineStageId }
    });
  } catch (guardError) {
    logger.warn("mutation-guard skipped", { component: "deals.bulk-update-stage", err: guardError });
    guardResult = null;
  }
  if (guardResult && !guardResult.ok) {
    return NextResponse.json(guardResult.body, { status: guardResult.status });
  }
  let progressService;
  try {
    progressService = container.resolve("progressService");
  } catch (resolveError) {
    logger.error("progressService resolve failed", { component: "deals.bulk-update-stage", err: resolveError });
    throw new Error(
      `progressService resolve failed: ${resolveError instanceof Error ? resolveError.message : String(resolveError)}`
    );
  }
  let progressJob;
  try {
    progressJob = await progressService.createJob(
      {
        jobType: "customers.deals.bulk_update_stage",
        name: translate(
          "customers.deals.kanban.bulk.changeStage.progress.name",
          "Move selected deals to a new stage"
        ),
        description: translate(
          "customers.deals.kanban.bulk.changeStage.progress.description",
          "{count} deals queued for stage update",
          { count: ids.length }
        ),
        totalCount: ids.length,
        cancellable: false,
        meta: {
          source: "customers.deals.bulk-update-stage",
          pipelineStageId: parsed.data.pipelineStageId
        }
      },
      {
        tenantId: auth.tenantId,
        organizationId: auth.orgId,
        userId: auth.sub
      }
    );
  } catch (createError) {
    logger.error("progressService.createJob failed", { component: "deals.bulk-update-stage", err: createError });
    throw new Error(
      `progressService.createJob failed: ${createError instanceof Error ? createError.message : String(createError)}`
    );
  }
  const queue = getCustomersQueue(CUSTOMERS_DEALS_BULK_UPDATE_STAGE_QUEUE);
  try {
    await queue.enqueue({
      progressJobId: progressJob.id,
      ids,
      pipelineStageId: parsed.data.pipelineStageId,
      scope: {
        organizationId: auth.orgId,
        tenantId: auth.tenantId,
        userId: auth.sub
      }
    });
  } catch (error) {
    await progressService.failJob(
      progressJob.id,
      {
        errorMessage: error instanceof Error ? error.message : translate("customers.errors.bulk_enqueue_failed", "Failed to enqueue bulk job")
      },
      {
        tenantId: auth.tenantId,
        organizationId: auth.orgId,
        userId: auth.sub
      }
    ).catch((failErr) => {
      logger.warn("failed to mark progress job as failed", { component: "deals.bulk-update-stage", err: failErr });
    });
    throw error;
  }
  if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
    await runCrudMutationGuardAfterSuccess(container, {
      tenantId: auth.tenantId,
      organizationId: auth.orgId,
      userId: auth.sub,
      resourceKind: "customers.deal",
      resourceId: ids.join(","),
      operation: "custom",
      requestMethod: req.method,
      requestHeaders: req.headers,
      metadata: guardResult.metadata ?? null
    });
  }
  return NextResponse.json(
    responseSchema.parse({
      ok: true,
      progressJobId: progressJob.id,
      message: translate(
        "customers.deals.kanban.bulk.changeStage.queued",
        "Bulk stage update started ({count} deals).",
        { count: ids.length }
      )
    }),
    { status: 202 }
  );
}
async function POST(req) {
  const { translate } = await resolveTranslations();
  try {
    return await postImpl(req, translate);
  } catch (error) {
    logger.error("route failed", { component: "deals.bulk-update-stage", err: error });
    return NextResponse.json(
      responseSchema.parse({
        ok: false,
        progressJobId: null,
        message: error instanceof Error ? error.message : translate("customers.errors.bulk_enqueue_failed", "Failed to enqueue bulk job")
      }),
      { status: 500 }
    );
  }
}
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
