import { pool } from "../config/db.js";

export async function ensureAuditTable(connection = pool) {
  await connection.query(`
    CREATE TABLE IF NOT EXISTS audit_logs (
      id INT AUTO_INCREMENT PRIMARY KEY,
      user_id INT NULL,
      username VARCHAR(100) NULL,
      action VARCHAR(80) NOT NULL,
      entity VARCHAR(80) NULL,
      entity_id VARCHAR(80) NULL,
      details JSON NULL,
      ip_address VARCHAR(80) NULL,
      user_agent VARCHAR(255) NULL,
      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      INDEX idx_audit_created (created_at),
      INDEX idx_audit_action (action),
      INDEX idx_audit_entity (entity)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  `);
}

export async function writeAuditLog(req, { action, entity = null, entityId = null, details = null } = {}) {
  try {
    await ensureAuditTable();
    await pool.query(
      `
      INSERT INTO audit_logs
        (user_id, username, action, entity, entity_id, details, ip_address, user_agent, created_at)
      VALUES
        (:userId, :username, :action, :entity, :entityId, :details, :ipAddress, :userAgent, NOW())
      `,
      {
        userId: req?.user?.id || null,
        username: req?.user?.username || req?.body?.username || null,
        action,
        entity,
        entityId,
        details: details ? JSON.stringify(details) : null,
        ipAddress: req?.ip || null,
        userAgent: req?.headers?.["user-agent"]?.slice(0, 255) || null
      }
    );
  } catch (error) {
    console.error("Audit log failed:", error.message);
  }
}
