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

export async function GET(): Promise<Response> {
  const auth = await requirePermission("incident:read", {
    action: "emergency.incident.list",
    targetType: "incident",
  });

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

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

  const data = await listEmergencyIncidentData(organizationId);
  return jsonSuccess("应急事件已加载", { data });
}

export async function POST(request: Request): Promise<Response> {
  const auth = await requirePermission("incident:manage", {
    action: "emergency.incident.create",
    targetType: "incident",
  });

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

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

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

  const incident = await createEmergencyIncident({ ...input.data, organizationId });
  if (isEmergencyMutationFailure(incident)) {
    return jsonFailure(incident.reason, incident.status);
  }

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

  return jsonSuccess("应急事件已创建", { incident }, 201);
}
