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

export async function GET(): Promise<Response> {
  const auth = await requirePermission("alert:read", { action: "alert.rule.list", targetType: "alert_rule" });
  if (!auth.success) {
    return auth.response;
  }

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后查看规则预警", 400);
  }

  const data = await listAlertCenterData(organizationId);
  return jsonSuccess("规则预警已加载", { data });
}

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

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

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

  const rule = await createAlertRule({ ...input.data, organizationId });
  if (isAlertMutationFailure(rule)) {
    return jsonFailure(rule.reason, rule.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "alert.rule.create",
    targetType: "alert_rule",
    targetId: rule.id,
    result: "success",
    reason: `创建预警规则：${rule.name}`,
  });

  return jsonSuccess("预警规则已创建", { rule }, 201);
}
