import { Prisma } from "@prisma/client";
import { prisma } from "@/lib/prisma";
import { writeAlert } from "@/modules/alert/service";

/**
 * 审计日志写入（task-094）
 * 失败仅 log，不阻断主流程
 */
export async function writeAudit(
  action: string,
  actorId: string,
  resource?: string,
  detail?: Record<string, unknown>,
): Promise<void> {
  try {
    await prisma.auditLog.create({
      data: {
        action,
        actorId,
        resource: resource ?? null,
        detailJson: detail
          ? (detail as Prisma.InputJsonValue)
          : undefined,
      },
    });
  } catch (error) {
    console.error(`[audit] 写入 ${action} 失败:`, error);
  }
}

/** 高危安全事件：audit + SECURITY 预警（task-105） */
export async function recordSecurityEvent(
  action: string,
  actorId: string,
  resource: string | undefined,
  detail: Record<string, unknown>,
): Promise<void> {
  await writeAudit(action, actorId, resource, detail);
  await writeAlert("SECURITY", {
    quoteId: typeof detail.quote_id === "string" ? detail.quote_id : undefined,
    detail: { ...detail, audit_action: action },
  });
}
