import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { deleteAlertRule, isAlertMutationFailure, updateAlertRule } from "@/modules/alerts/server/operations";
import { validateAlertRuleInput } from "@/modules/alerts/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("alert:manage", { action: "alert.rule.update", targetType: "alert_rule", targetId: id });
  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 updateAlertRule({ ...input.data, id, organizationId });
  if (isAlertMutationFailure(rule)) {
    return jsonFailure(rule.reason, rule.status);
  }

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

  return jsonSuccess("预警规则已更新", { rule });
}

export async function DELETE(_request: Request, context: RouteContext): Promise<Response> {
  const { id } = await context.params;
  const auth = await requirePermission("alert:manage", { action: "alert.rule.delete", targetType: "alert_rule", targetId: id });
  if (!auth.success) {
    return auth.response;
  }

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

  const rule = await deleteAlertRule({ id, organizationId });
  if (isAlertMutationFailure(rule)) {
    return jsonFailure(rule.reason, rule.status);
  }

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

  return jsonSuccess("预警规则已删除", { rule });
}
