import apiLogService from '../services/apiLogService.js';
import HttpError from '../exceptions/HttpError.js';

class ApiLogController {
  /**
   * GET /api/logs
   * Get API logs with optional filters
   */
  async getLogs(req, res, next) {
    try {
      const {
        userId,
        logType,
        method,
        path,
        statusCode,
        startDate,
        endDate,
        limit = 100,
        offset = 0
      } = req.query;

      const result = await apiLogService.getLogs({
        userId: userId ? parseInt(userId) : null,
        logType,
        method,
        path,
        statusCode: statusCode ? parseInt(statusCode) : null,
        startDate,
        endDate,
        limit: parseInt(limit),
        offset: parseInt(offset)
      });

      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      next(error);
    }
  }

  /**
   * GET /api/logs/:id
   * Get a single log entry by ID
   */
  async getLogById(req, res, next) {
    try {
      const { id } = req.params;
      const log = await apiLogService.getLogById(parseInt(id));

      if (!log) {
        throw new HttpError('Log entry not found', 404);
      }

      res.json({
        success: true,
        data: log
      });
    } catch (error) {
      next(error);
    }
  }

  /**
   * GET /api/logs/scheduler/last-executions
   * Get last execution info for scheduler jobs
   */
  async getLastSchedulerExecutions(req, res, next) {
    try {
      const { clubId } = req.query;
      const results = await apiLogService.getLastSchedulerExecutions(clubId ? parseInt(clubId) : null);
      res.json({
        success: true,
        data: results
      });
    } catch (error) {
      next(error);
    }
  }
}

export default new ApiLogController();

