const prisma = require('../config/db');

const SENSITIVE = new Set(['password', 'passwordHash', 'token', 'paymentKey', 'secretKey']);

function maskBody(body) {
  if (!body || typeof body !== 'object') return body;
  const masked = { ...body };
  for (const key of Object.keys(masked)) {
    if (SENSITIVE.has(key)) masked[key] = '***';
  }
  return masked;
}

// 중요 행동에 명시적으로 호출하는 감사 로그 저장 함수
async function writeAuditLog({ userId, action, targetType, targetId, req, metadata, responseStatus }) {
  try {
    await prisma.auditLog.create({
      data: {
        userId:        userId || null,
        action,
        targetType:    targetType || null,
        targetId:      targetId || null,
        ipAddress:     req?.ip || req?.headers?.['x-forwarded-for'] || 'unknown',
        userAgent:     req?.headers?.['user-agent'] || null,
        requestMethod: req?.method || null,
        requestPath:   req?.originalUrl || null,
        requestBody:   req?.body ? maskBody(req.body) : null,
        responseStatus: responseStatus || null,
        metadata:      metadata || null,
      },
    });
  } catch (err) {
    console.error('AuditLog write failed:', err.message);
  }
}

module.exports = { writeAuditLog };
