import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { isEmergencyMutationFailure, updateEmergencyIncidentStatus } from "@/modules/emergency/server/operations";
import { validateEmergencyIncidentStatusUpdateInput } from "@/modules/emergency/types";

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

export async function PATCH(request: Request, context: RouteContext): Promise<Response> {
  const { id } = await context.params;
  const auth = await requirePermission("incident:manage", {
    action: "emergency.incident.update",
    targetType: "incident",
    targetId: id,
  });

  if (!auth.success) {
    return auth.response;
  }

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后处理应急事件", 400);
  }

  const input = validateEmergencyIncidentStatusUpdateInput(await readJsonBody(request));
  if (!input.success) {
    return jsonFailure(input.reason);
  }

  const incident = await updateEmergencyIncidentStatus({
    ...input.data,
    id,
    organizationId,
    accountId: auth.context.account.id,
  });
  if (isEmergencyMutationFailure(incident)) {
    return jsonFailure(incident.reason, incident.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "emergency.incident.update",
    targetType: "incident",
    targetId: incident.id,
    result: "success",
    reason: `处理应急事件：${incident.title}`,
  });

  return jsonSuccess("应急事件已更新", { incident });
}
