/**
 * LoteController - Controller de lotes
 *
 * Endpoints REST para gestión de lotes/terrenos.
 *
 * @module Construction
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { LoteService, CreateLoteDto, UpdateLoteDto } from '../services/lote.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { Lote } from '../entities/lote.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 lotes
 */
export function createLoteController(dataSource: DataSource): Router {
  const router = Router();

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

  // Servicios
  const loteService = new LoteService(loteRepository);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

  /**
   * GET /lotes
   * Listar lotes
   */
  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 manzanaId = req.query.manzanaId as string;
      const prototipoId = req.query.prototipoId as string;

      const result = await loteService.findAll({ tenantId, page, limit, search, status, manzanaId, prototipoId });

      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 /lotes/stats
   * Estadísticas de lotes por estado
   */
  router.get('/stats', 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 manzanaId = req.query.manzanaId as string;
      const stats = await loteService.getStatsByStatus(tenantId, manzanaId);

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

  /**
   * GET /lotes/:id
   * Obtener lote 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 lote = await loteService.findById(req.params.id, tenantId);
      if (!lote) {
        res.status(404).json({ error: 'Not Found', message: 'Lot not found' });
        return;
      }

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

  /**
   * POST /lotes
   * Crear lote
   */
  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: CreateLoteDto = req.body;

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

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

  /**
   * PATCH /lotes/:id
   * Actualizar lote
   */
  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: UpdateLoteDto = req.body;
      const lote = await loteService.update(req.params.id, tenantId, dto, req.user?.sub);
      res.status(200).json({ success: true, data: lote });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message === 'Lot 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);
    }
  });

  /**
   * PATCH /lotes/:id/prototipo
   * Asignar prototipo a lote
   */
  router.patch('/:id/prototipo', 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 { prototipoId } = req.body;
      if (!prototipoId) {
        res.status(400).json({ error: 'Bad Request', message: 'prototipoId is required' });
        return;
      }

      const lote = await loteService.assignPrototipo(req.params.id, tenantId, prototipoId, req.user?.sub);
      res.status(200).json({ success: true, data: lote });
    } catch (error) {
      if (error instanceof Error && error.message === 'Lot not found') {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * PATCH /lotes/:id/status
   * Cambiar estado del lote
   */
  router.patch('/:id/status', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'finance'), 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 { status } = req.body;
      if (!status) {
        res.status(400).json({ error: 'Bad Request', message: 'status is required' });
        return;
      }

      const validStatuses = ['available', 'reserved', 'sold', 'blocked', 'in_construction'];
      if (!validStatuses.includes(status)) {
        res.status(400).json({ error: 'Bad Request', message: `Invalid status. Must be one of: ${validStatuses.join(', ')}` });
        return;
      }

      const lote = await loteService.changeStatus(req.params.id, tenantId, status, req.user?.sub);
      res.status(200).json({ success: true, data: lote });
    } catch (error) {
      if (error instanceof Error && error.message === 'Lot not found') {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * DELETE /lotes/:id
   * Eliminar lote
   */
  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 loteService.delete(req.params.id, tenantId, req.user?.sub);
      res.status(200).json({ success: true, message: 'Lot deleted' });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message === 'Lot not found') {
          res.status(404).json({ error: 'Not Found', message: error.message });
          return;
        }
        if (error.message === 'Cannot delete a sold lot') {
          res.status(400).json({ error: 'Bad Request', message: error.message });
          return;
        }
      }
      next(error);
    }
  });

  return router;
}

export default createLoteController;
