/**
 * FuelLogController - Controlador de Registro de Combustible
 *
 * Endpoints para gestión de cargas de combustible y rendimiento.
 *
 * @module Assets (MAE-015)
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { FuelLogService } from '../services';

export function createFuelLogController(dataSource: DataSource): Router {
  const router = Router();
  const service = new FuelLogService(dataSource);

  /**
   * GET /
   * Lista registros de combustible con filtros
   */
  router.get('/', async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;

      const filters = {
        assetId: req.query.assetId as string,
        projectId: req.query.projectId as string,
        fuelType: req.query.fuelType as string,
        fromDate: req.query.fromDate ? new Date(req.query.fromDate as string) : undefined,
        toDate: req.query.toDate ? new Date(req.query.toDate as string) : undefined,
      };

      const pagination = {
        page: parseInt(req.query.page as string) || 1,
        limit: parseInt(req.query.limit as string) || 20,
      };

      const result = await service.findAll(tenantId, filters, pagination);
      res.json(result);
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /statistics/:assetId
   * Obtiene estadísticas de combustible para un activo
   */
  router.get('/statistics/:assetId', async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;

      const fromDate = req.query.fromDate ? new Date(req.query.fromDate as string) : undefined;
      const toDate = req.query.toDate ? new Date(req.query.toDate as string) : undefined;

      const stats = await service.getAssetStatistics(tenantId, req.params.assetId, fromDate, toDate);
      res.json(stats);
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /:id
   * Obtiene un registro por ID
   */
  router.get('/:id', async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;

      const fuelLog = await service.findById(tenantId, req.params.id);
      if (!fuelLog) {
        res.status(404).json({ error: 'Registro de combustible no encontrado' });
        return;
      }

      res.json(fuelLog);
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /
   * Crea un nuevo registro de combustible
   */
  router.post('/', async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;
      const userId = (req as any).user?.id;

      const fuelLog = await service.create(tenantId, req.body, userId);
      res.status(201).json(fuelLog);
    } catch (error) {
      next(error);
    }
  });

  /**
   * DELETE /:id
   * Elimina un registro de combustible
   */
  router.delete('/:id', async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;

      const deleted = await service.delete(tenantId, req.params.id);
      if (!deleted) {
        res.status(404).json({ error: 'Registro de combustible no encontrado' });
        return;
      }

      res.status(204).send();
    } catch (error) {
      next(error);
    }
  });

  return router;
}
