import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { deleteAlertTrigger, isAlertMutationFailure, updateAlertTrigger } from "@/modules/alerts/server/operations";
import { validateAlertTriggerInput } 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.trigger.update", targetType: "alert_trigger", targetId: id });
  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 updateAlertTrigger({ ...input.data, id, 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.update",
    targetType: "alert_trigger",
    targetId: trigger.id,
    result: "success",
    reason: `更新预警触发记录：${trigger.title}`,
  });

  return jsonSuccess("预警触发记录已更新", { trigger });
}

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

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

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

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

  return jsonSuccess("预警触发记录已删除", { trigger });
}
