/**
 * Logger Middleware
 * Custom logging for requests and responses
 */

const fs = require("fs");
const path = require("path");

/**
 * Create log directory if it doesn't exist
 */
const logDir = path.join(__dirname, "../logs");
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

/**
 * Get current timestamp
 */
const getTimestamp = () => {
  return new Date().toISOString();
};

/**
 * Format log message
 */
const formatLogMessage = (req, res, responseTime) => {
  return {
    timestamp: getTimestamp(),
    method: req.method,
    url: req.originalUrl,
    status: res.statusCode,
    responseTime: `${responseTime}ms`,
    ip: req.ip || req.connection.remoteAddress,
    userAgent: req.headers["user-agent"],
    userId: req.user?.id || null,
  };
};

/**
 * Write to log file
 */
const writeToFile = (logData, type = "access") => {
  const date = new Date().toISOString().split("T")[0];
  const logFile = path.join(logDir, `${type}-${date}.log`);
  const logLine = JSON.stringify(logData) + "\n";

  fs.appendFile(logFile, logLine, (err) => {
    if (err) console.error("Error writing to log file:", err);
  });
};

/**
 * Request Logger Middleware
 */
const requestLogger = (req, res, next) => {
  const startTime = Date.now();

  // Log request start
  if (process.env.NODE_ENV === "development") {
    console.log(`[${getTimestamp()}] ${req.method} ${req.originalUrl}`);
  }

  // Capture response finish
  res.on("finish", () => {
    const responseTime = Date.now() - startTime;
    const logData = formatLogMessage(req, res, responseTime);

    // Console log in development
    if (process.env.NODE_ENV === "development") {
      const statusColor = res.statusCode >= 400 ? "\x1b[31m" : "\x1b[32m";
      console.log(
        `[${logData.timestamp}] ${req.method} ${req.originalUrl} ${statusColor}${res.statusCode}\x1b[0m ${responseTime}ms`,
      );
    }

    // Write to file
    writeToFile(logData, "access");

    // Log errors separately
    if (res.statusCode >= 400) {
      writeToFile(logData, "error");
    }
  });

  next();
};

/**
 * Error Logger
 */
const errorLogger = (err, req, res, next) => {
  const errorData = {
    timestamp: getTimestamp(),
    method: req.method,
    url: req.originalUrl,
    error: {
      message: err.message,
      stack: process.env.NODE_ENV === "development" ? err.stack : undefined,
      code: err.code,
    },
    ip: req.ip,
    userId: req.user?.id || null,
  };

  // Console log
  console.error(`[ERROR] ${getTimestamp()}:`, err.message);

  // Write to error log
  writeToFile(errorData, "error");

  next(err);
};

/**
 * Activity Logger - Log specific actions
 */
const logActivity = (action, details, userId = null) => {
  const activityData = {
    timestamp: getTimestamp(),
    action,
    details,
    userId,
  };

  writeToFile(activityData, "activity");
};

module.exports = {
  requestLogger,
  errorLogger,
  logActivity,
};
