import { db } from "@/db";
import { auditLogs } from "@/db/schema";

/**
 * Ghi một dòng vào nhật ký thao tác. Nội dung KHÔNG được chứa mật khẩu, mã đặt lại mật khẩu hay bất kỳ bí mật nào.
 * `entityId` là mã của bản ghi chính (để xem lại toàn bộ lịch sử của nó); bản ghi con ghi kèm mã cha nếu cần.
 */
export async function writeAudit(
  session: { tenantId: string; userId: string },
  action: "CREATE" | "UPDATE" | "DELETE" | "IMPORT" | "EXPORT",
  entityType: string,
  entityId: string | null,
  payload: Record<string, unknown>,
) {
  await db.insert(auditLogs).values({ tenantId: session.tenantId, userId: session.userId, action, entityType, entityId, payload });
}

/**
 * So sánh trạng thái trước/sau của một bản ghi, dùng cho nhật ký sửa đổi chi tiết
 * (yêu cầu mục 6) — chỉ ghi lại những trường thực sự đổi, không phải toàn bộ bản ghi.
 */
export function diffFields<T extends Record<string, unknown>>(
  before: T,
  after: T,
): Record<string, { from: unknown; to: unknown }> {
  const diff: Record<string, { from: unknown; to: unknown }> = {};
  for (const key of Object.keys(after)) {
    const a = before[key];
    const b = after[key];
    const same =
      a instanceof Date && b instanceof Date
        ? a.getTime() === b.getTime()
        : JSON.stringify(a) === JSON.stringify(b);
    if (!same) diff[key] = { from: a ?? null, to: b ?? null };
  }
  return diff;
}
