const express = require('express');
const fs = require('fs');
const fsp = require('fs').promises;
const { exists } = require('../src/utilities/fs-helpers');
const { paginate, parsePaginationParams } = require('../src/utilities/pagination');
const { success } = require('../src/utils/responses');

/**
 * Error logs routes factory
 * @param {Object} deps - Explicit dependencies
 * @param {string} deps.ERROR_LOG_FILE - Path to error log file
 * @param {Object} deps.auditLogger - Audit logger instance
 * @param {Function} deps.asyncHandler - Async route handler wrapper
 * @returns {express.Router}
 */
module.exports = function({ ERROR_LOG_FILE, auditLogger, asyncHandler }) {
  const router = express.Router();

  // Get error logs
  router.get('/error-logs', asyncHandler(async (req, res) => {
    if (!await exists(ERROR_LOG_FILE)) {
      return success(res, { logs: [] });
    }

    const logContent = await fsp.readFile(ERROR_LOG_FILE, 'utf8');
      const logEntries = logContent.split('='.repeat(80)).filter(entry => entry.trim());

      const logs = logEntries.map(entry => {
        const lines = entry.trim().split('\n');
        const firstLine = lines[0] || '';
        const match = firstLine.match(/\[(.*?)\] (.*?): (.*)/);

        if (match) {
          return {
            timestamp: match[1],
            context: match[2],
            error: match[3]
          };
        }
        return null;
      }).filter(Boolean);

    success(res, { logs: logs.slice(-50).reverse() });
  }, 'error-logs-get'));

  // Clear error logs
  router.delete('/error-logs', asyncHandler(async (req, res) => {
    if (await exists(ERROR_LOG_FILE)) {
      await fsp.writeFile(ERROR_LOG_FILE, '');
    }
    success(res, { message: 'Error logs cleared' });
  }, 'error-logs-clear'));

  // Audit log
  router.get('/audit-logs', asyncHandler(async (req, res) => {
    const paginationParams = parsePaginationParams(req.query);
    const action = req.query.action || '';
    if (paginationParams) {
      // When paginating, fetch all matching entries and let pagination slice
      const entries = await auditLogger.query({ limit: Number.MAX_SAFE_INTEGER, offset: 0, action });
      const result = paginate(entries, paginationParams);
      success(res, { entries: result.data, pagination: result.pagination });
    } else {
      const limit = parseInt(req.query.limit) || 50;
      const offset = parseInt(req.query.offset) || 0;
      const entries = await auditLogger.query({ limit, offset, action });
      success(res, { entries });
    }
  }, 'audit-log'));

  router.delete('/audit-logs', asyncHandler(async (req, res) => {
    await auditLogger.clear();
    success(res, { message: 'Audit log cleared' });
  }, 'audit-log-clear'));

  return router;
};
