import { parseAdminAuth } from "@/lib/api/admin-auth-context";
import { fail, ok } from "@/lib/response";
import { AuthError } from "@/modules/auth/errors";
import { requirePermission } from "@/modules/auth/rbac";
import { pauseWorker } from "@/workers/rpa/worker-state";

type PauseBody = {
  worker_id?: unknown;
  duration_minutes?: unknown;
};

export async function POST(request: Request) {
  let auth;
  try {
    auth = parseAdminAuth(request);
    requirePermission(auth, "rpa:operate");
  } catch (error) {
    if (error instanceof AuthError) {
      return fail(error.code, error.message, error.httpStatus);
    }
    throw error;
  }

  void auth;

  let body: PauseBody;
  try {
    body = (await request.json()) as PauseBody;
  } catch {
    return fail("VALIDATION_FAILED", "请求体格式无效", 400);
  }

  const workerId =
    typeof body.worker_id === "string" ? body.worker_id.trim() : "";
  const durationMinutes =
    typeof body.duration_minutes === "number" &&
    Number.isFinite(body.duration_minutes)
      ? Math.floor(body.duration_minutes)
      : null;

  if (!workerId) {
    return fail("VALIDATION_FAILED", "请填写 worker_id", 400);
  }
  if (durationMinutes === null || durationMinutes < 1 || durationMinutes > 120) {
    return fail("VALIDATION_FAILED", "暂停时长须为 1~120 分钟", 400);
  }

  await pauseWorker(workerId, durationMinutes);

  return ok({
    worker_id: workerId,
    duration_minutes: durationMinutes,
    message: "Worker 已暂停",
  });
}
