/**
 * PrototipoController - Controller de prototipos
 *
 * Endpoints REST para gestión de prototipos de vivienda.
 *
 * @module Construction
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { PrototipoService, CreatePrototipoDto, UpdatePrototipoDto } from '../services/prototipo.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { Prototipo } from '../entities/prototipo.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 prototipos
 */
export function createPrototipoController(dataSource: DataSource): Router {
  const router = Router();

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

  // Servicios
  const prototipoService = new PrototipoService(prototipoRepository);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

  /**
   * GET /prototipos
   * Listar prototipos
   */
  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 type = req.query.type as string;
      const isActive = req.query.isActive === 'true' ? true : req.query.isActive === 'false' ? false : undefined;

      const result = await prototipoService.findAll({ tenantId, page, limit, search, type, isActive });

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

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

  /**
   * POST /prototipos
   * Crear prototipo
   */
  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: CreatePrototipoDto = req.body;

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

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

  /**
   * PATCH /prototipos/:id
   * Actualizar prototipo
   */
  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: UpdatePrototipoDto = req.body;
      const prototipo = await prototipoService.update(req.params.id, tenantId, dto, req.user?.sub);
      res.status(200).json({ success: true, data: prototipo });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message === 'Prototype not found') {
          res.status(404).json({ error: 'Not Found', message: error.message });
          return;
        }
        if (error.message === 'Prototype code already exists') {
          res.status(409).json({ error: 'Conflict', message: error.message });
          return;
        }
      }
      next(error);
    }
  });

  /**
   * DELETE /prototipos/:id
   * Eliminar prototipo
   */
  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 prototipoService.delete(req.params.id, tenantId, req.user?.sub);
      res.status(200).json({ success: true, message: 'Prototype deleted' });
    } catch (error) {
      if (error instanceof Error && error.message === 'Prototype not found') {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  return router;
}

export default createPrototipoController;
