import { parseAdminAuth } from "@/lib/api/admin-auth-context";
import { prisma } from "@/lib/prisma";
import { fail, ok } from "@/lib/response";
import { AuthError } from "@/modules/auth/errors";
import { requirePermission } from "@/modules/auth/rbac";
import { serializeAlert } from "@/modules/alert/serializer";

type RouteContext = {
  params: Promise<{ id: string }>;
};

function parseAlertId(raw: string): bigint | null {
  if (!/^\d+$/.test(raw)) {
    return null;
  }
  try {
    return BigInt(raw);
  } catch {
    return null;
  }
}

/** POST /api/alerts/{id}/resolve — 标记预警已处理（task-057） */
export async function POST(request: Request, context: RouteContext) {
  let auth;
  try {
    auth = parseAdminAuth(request);
    requirePermission(auth, "alert:read");
  } catch (error) {
    if (error instanceof AuthError) {
      return fail(error.code, error.message, error.httpStatus);
    }
    throw error;
  }

  const { id: idRaw } = await context.params;
  const alertId = parseAlertId(idRaw);
  if (alertId === null) {
    return fail("VALIDATION_FAILED", "无效的预警编号", 400);
  }

  let body: { resolver_id?: unknown } = {};
  try {
    const text = await request.text();
    if (text.trim()) {
      body = JSON.parse(text) as { resolver_id?: unknown };
    }
  } catch {
    return fail("VALIDATION_FAILED", "请求体格式无效", 400);
  }

  const resolverId =
    typeof body.resolver_id === "string" && body.resolver_id.trim()
      ? body.resolver_id.trim()
      : auth.userId;

  const existing = await prisma.alertLog.findUnique({
    where: { id: alertId },
  });

  if (!existing) {
    return fail("ALERT_NOT_FOUND", "预警不存在", 404);
  }

  const updated = await prisma.alertLog.update({
    where: { id: alertId },
    data: {
      status: "resolved",
      resolverId,
      resolvedAt: new Date(),
    },
  });

  return ok(serializeAlert(updated));
}
