import { prisma } from '../models';
import { Request } from 'express';
import { Prisma } from '@prisma/client';

export async function writeAudit(
  req: Request,
  action: string,
  tableName: string,
  recordId: string,
  oldValue?: Prisma.JsonValue,
  newValue?: Prisma.JsonValue,
  backdateOtp?: string
): Promise<void> {
  if (!req.user) return;
  const ip = (req.headers['x-forwarded-for'] as string)?.split(',')[0]?.trim() || req.socket.remoteAddress || '';
  await prisma.auditLog.create({
    data: {
      user_id: req.user.id,
      user_name: req.user.full_name,
      user_role: req.user.role,
      action,
      table_name: tableName,
      record_id: recordId,
      old_value: oldValue === undefined ? Prisma.JsonNull : (oldValue as Prisma.InputJsonValue),
      new_value: newValue === undefined ? Prisma.JsonNull : (newValue as Prisma.InputJsonValue),
      backdate_otp_used: backdateOtp,
      ip_address: ip,
      user_agent: req.headers['user-agent'] ?? '',
    },
  });
}
