/**
 * Fleet Controller
 * Mecánicas Diesel - ERP Suite
 *
 * REST API endpoints for fleet management.
 */

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

interface TenantRequest extends Request {
  tenantId?: string;
  userId?: string;
}

export function createFleetController(dataSource: DataSource): Router {
  const router = Router();
  const service = new FleetService(dataSource);

  const extractTenant = (req: TenantRequest, res: Response, next: NextFunction) => {
    const tenantId = req.headers['x-tenant-id'] as string;
    if (!tenantId) {
      return res.status(400).json({ error: 'Tenant ID is required' });
    }
    req.tenantId = tenantId;
    req.userId = req.headers['x-user-id'] as string;
    next();
  };

  router.use(extractTenant);

  /**
   * Create a new fleet
   * POST /api/fleets
   */
  router.post('/', async (req: TenantRequest, res: Response) => {
    try {
      const fleet = await service.create(req.tenantId!, req.body);
      res.status(201).json(fleet);
    } catch (error) {
      res.status(400).json({ error: (error as Error).message });
    }
  });

  /**
   * List fleets
   * GET /api/fleets
   */
  router.get('/', async (req: TenantRequest, res: Response) => {
    try {
      const pagination = {
        page: parseInt(req.query.page as string, 10) || 1,
        limit: Math.min(parseInt(req.query.limit as string, 10) || 20, 100),
      };

      const result = await service.findAll(req.tenantId!, pagination);
      res.json(result);
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

  /**
   * Get active fleets
   * GET /api/fleets/active
   */
  router.get('/active', async (req: TenantRequest, res: Response) => {
    try {
      const fleets = await service.findActive(req.tenantId!);
      res.json(fleets);
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

  /**
   * Get a single fleet
   * GET /api/fleets/:id
   */
  router.get('/:id', async (req: TenantRequest, res: Response) => {
    try {
      const fleet = await service.findById(req.tenantId!, req.params.id);
      if (!fleet) {
        return res.status(404).json({ error: 'Fleet not found' });
      }
      res.json(fleet);
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

  /**
   * Get fleet with statistics
   * GET /api/fleets/:id/stats
   */
  router.get('/:id/stats', async (req: TenantRequest, res: Response) => {
    try {
      const result = await service.getFleetWithStats(req.tenantId!, req.params.id);
      if (!result) {
        return res.status(404).json({ error: 'Fleet not found' });
      }
      res.json(result);
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

  /**
   * Update fleet
   * PATCH /api/fleets/:id
   */
  router.patch('/:id', async (req: TenantRequest, res: Response) => {
    try {
      const fleet = await service.update(req.tenantId!, req.params.id, req.body);
      if (!fleet) {
        return res.status(404).json({ error: 'Fleet not found' });
      }
      res.json(fleet);
    } catch (error) {
      res.status(400).json({ error: (error as Error).message });
    }
  });

  /**
   * Deactivate fleet
   * DELETE /api/fleets/:id
   */
  router.delete('/:id', async (req: TenantRequest, res: Response) => {
    try {
      const success = await service.deactivate(req.tenantId!, req.params.id);
      if (!success) {
        return res.status(404).json({ error: 'Fleet not found' });
      }
      res.status(204).send();
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

  /**
   * Add vehicle to fleet
   * POST /api/fleets/:id/vehicles/:vehicleId
   */
  router.post('/:id/vehicles/:vehicleId', async (req: TenantRequest, res: Response) => {
    try {
      const success = await service.addVehicle(req.tenantId!, req.params.id, req.params.vehicleId);
      if (!success) {
        return res.status(404).json({ error: 'Fleet or vehicle not found' });
      }
      res.status(204).send();
    } catch (error) {
      res.status(400).json({ error: (error as Error).message });
    }
  });

  /**
   * Remove vehicle from fleet
   * DELETE /api/fleets/:id/vehicles/:vehicleId
   */
  router.delete('/:id/vehicles/:vehicleId', async (req: TenantRequest, res: Response) => {
    try {
      const success = await service.removeVehicle(req.tenantId!, req.params.id, req.params.vehicleId);
      if (!success) {
        return res.status(404).json({ error: 'Vehicle not found in fleet' });
      }
      res.status(204).send();
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

  return router;
}
