/**
 * EtapaController - Controller de etapas
 *
 * Endpoints REST para gestión de etapas de fraccionamientos.
 *
 * @module Construction
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { EtapaService, CreateEtapaDto, UpdateEtapaDto } from '../services/etapa.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { Etapa } from '../entities/etapa.entity';
import { User } from '../../core/entities/user.entity';
import { Tenant } from '../../core/entities/tenant.entity';
import { RefreshToken } from '../../auth/entities/refresh-token.entity';

/**
 * Crear router de etapas
 */
export function createEtapaController(dataSource: DataSource): Router {
  const router = Router();

  // Repositorios
  const etapaRepository = dataSource.getRepository(Etapa);
  const userRepository = dataSource.getRepository(User);
  const tenantRepository = dataSource.getRepository(Tenant);
  const refreshTokenRepository = dataSource.getRepository(RefreshToken);

  // Servicios
  const etapaService = new EtapaService(etapaRepository);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

  /**
   * GET /etapas
   * Listar etapas
   */
  router.get('/', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const page = parseInt(req.query.page as string) || 1;
      const limit = Math.min(parseInt(req.query.limit as string) || 20, 100);
      const search = req.query.search as string;
      const status = req.query.status as string;
      const fraccionamientoId = req.query.fraccionamientoId as string;

      const result = await etapaService.findAll({ tenantId, page, limit, search, status, fraccionamientoId });

      res.status(200).json({
        success: true,
        data: result.items,
        pagination: {
          page,
          limit,
          total: result.total,
          totalPages: Math.ceil(result.total / limit),
        },
      });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /etapas/:id
   * Obtener etapa por ID
   */
  router.get('/:id', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const etapa = await etapaService.findById(req.params.id, tenantId);
      if (!etapa) {
        res.status(404).json({ error: 'Not Found', message: 'Stage not found' });
        return;
      }

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

  /**
   * POST /etapas
   * Crear etapa
   */
  router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', 'director'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const dto: CreateEtapaDto = req.body;

      if (!dto.fraccionamientoId || !dto.code || !dto.name) {
        res.status(400).json({ error: 'Bad Request', message: 'fraccionamientoId, code and name are required' });
        return;
      }

      const etapa = await etapaService.create(tenantId, dto, req.user?.sub);
      res.status(201).json({ success: true, data: etapa });
    } catch (error) {
      if (error instanceof Error && error.message.includes('already exists')) {
        res.status(409).json({ error: 'Conflict', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * PATCH /etapas/:id
   * Actualizar etapa
   */
  router.patch('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', 'director'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const dto: UpdateEtapaDto = req.body;
      const etapa = await etapaService.update(req.params.id, tenantId, dto, req.user?.sub);
      res.status(200).json({ success: true, data: etapa });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message === 'Stage not found') {
          res.status(404).json({ error: 'Not Found', message: error.message });
          return;
        }
        if (error.message.includes('already exists')) {
          res.status(409).json({ error: 'Conflict', message: error.message });
          return;
        }
      }
      next(error);
    }
  });

  /**
   * DELETE /etapas/:id
   * Eliminar etapa
   */
  router.delete('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      await etapaService.delete(req.params.id, tenantId, req.user?.sub);
      res.status(200).json({ success: true, message: 'Stage deleted' });
    } catch (error) {
      if (error instanceof Error && error.message === 'Stage not found') {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  return router;
}

export default createEtapaController;
