import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { createAlertTrigger, isAlertMutationFailure } from "@/modules/alerts/server/operations";
import { validateAlertTriggerInput } from "@/modules/alerts/types";

export async function POST(request: Request): Promise<Response> {
  const auth = await requirePermission("alert:manage", { action: "alert.trigger.create", targetType: "alert_trigger" });
  if (!auth.success) {
    return auth.response;
  }

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后维护触发记录", 400);
  }

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

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

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "alert.trigger.create",
    targetType: "alert_trigger",
    targetId: trigger.id,
    result: "success",
    reason: `创建预警触发记录：${trigger.title}`,
  });

  return jsonSuccess("预警触发记录已创建", { trigger }, 201);
}
