import { db } from '../config/database.js';
import { auditLogs } from '../db/schema.js';
import { logger } from '../utils/logger.js';

/**
 * Zaloguje audit event
 */
export const logAuditEvent = async ({
  userId = null,
  action,
  resource,
  resourceId = null,
  oldValue = null,
  newValue = null,
  ipAddress = null,
  userAgent = null,
  success = true,
  errorMessage = null,
}) => {
  try {
    await db.insert(auditLogs).values({
      userId,
      action,
      resource,
      resourceId,
      oldValue: oldValue ? JSON.stringify(oldValue) : null,
      newValue: newValue ? JSON.stringify(newValue) : null,
      ipAddress,
      userAgent,
      success,
      errorMessage,
    });

    logger.audit(
      `${action} on ${resource}${resourceId ? ` (${resourceId})` : ''} ${success ? 'SUCCESS' : 'FAILED'}${userId ? ` by user ${userId}` : ''}`
    );
  } catch (error) {
    logger.error('Failed to log audit event', error);
  }
};

/**
 * Pomocné funkcie pre špecifické audit eventy
 */

export const logLoginAttempt = async (username, success, ipAddress, userAgent, errorMessage = null) => {
  await logAuditEvent({
    action: 'login_attempt',
    resource: 'user',
    resourceId: username,
    ipAddress,
    userAgent,
    success,
    errorMessage,
  });
};

export const logPasswordChange = async (userId, ipAddress, userAgent) => {
  await logAuditEvent({
    userId,
    action: 'password_change',
    resource: 'user',
    resourceId: userId,
    ipAddress,
    userAgent,
    success: true,
  });
};

export const logEmailLink = async (userId, email, ipAddress, userAgent) => {
  await logAuditEvent({
    userId,
    action: 'email_linked',
    resource: 'user',
    resourceId: userId,
    newValue: { email },
    ipAddress,
    userAgent,
    success: true,
  });
};

export const logRoleChange = async (adminId, userId, oldRole, newRole, ipAddress, userAgent) => {
  await logAuditEvent({
    userId: adminId,
    action: 'role_change',
    resource: 'user',
    resourceId: userId,
    oldValue: { role: oldRole },
    newValue: { role: newRole },
    ipAddress,
    userAgent,
    success: true,
  });
};

export const logUserCreation = async (adminId, newUserId, username, role, ipAddress, userAgent) => {
  await logAuditEvent({
    userId: adminId,
    action: 'user_created',
    resource: 'user',
    resourceId: newUserId,
    newValue: { username, role },
    ipAddress,
    userAgent,
    success: true,
  });
};
