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

module.exports = function(ctx) {
  const router = express.Router();

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

    const logContent = await fsp.readFile(ctx.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);

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

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

  // Audit log
  router.get('/audit-logs', ctx.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 ctx.auditLogger.query({ limit: Number.MAX_SAFE_INTEGER, offset: 0, action });
      const result = paginate(entries, paginationParams);
      res.json({ success: true, entries: result.data, pagination: result.pagination });
    } else {
      const limit = parseInt(req.query.limit) || 50;
      const offset = parseInt(req.query.offset) || 0;
      const entries = await ctx.auditLogger.query({ limit, offset, action });
      res.json({ success: true, entries });
    }
  }, 'audit-log'));

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

  return router;
};
