/**
 * ConceptoController - Controller de conceptos de obra
 *
 * Endpoints REST para gestión del catálogo de conceptos.
 *
 * @module Budgets
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { ConceptoService, CreateConceptoDto, UpdateConceptoDto } from '../services/concepto.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { Concepto } from '../entities/concepto.entity';
import { User } from '../../core/entities/user.entity';
import { Tenant } from '../../core/entities/tenant.entity';
import { RefreshToken } from '../../auth/entities/refresh-token.entity';
import { ServiceContext } from '../../../shared/services/base.service';

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

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

  // Servicios
  const conceptoService = new ConceptoService(conceptoRepository);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

  // Helper para crear contexto de servicio
  const getContext = (req: Request): ServiceContext => {
    if (!req.tenantId) {
      throw new Error('Tenant ID is required');
    }
    return {
      tenantId: req.tenantId,
      userId: req.user?.sub,
    };
  };

  /**
   * GET /conceptos
   * Listar conceptos raíz
   */
  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) || 50, 100);

      const result = await conceptoService.findRootConceptos(getContext(req), page, limit);

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

  /**
   * GET /conceptos/search
   * Buscar conceptos por código o nombre
   */
  router.get('/search', 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 term = req.query.q as string;
      if (!term || term.length < 2) {
        res.status(400).json({ error: 'Bad Request', message: 'Search term must be at least 2 characters' });
        return;
      }

      const limit = Math.min(parseInt(req.query.limit as string) || 20, 50);
      const conceptos = await conceptoService.search(getContext(req), term, limit);

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

  /**
   * GET /conceptos/tree
   * Obtener árbol de conceptos
   */
  router.get('/tree', 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 rootId = req.query.rootId as string;
      const tree = await conceptoService.getConceptoTree(getContext(req), rootId);

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

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

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

  /**
   * GET /conceptos/:id/children
   * Obtener hijos de un concepto
   */
  router.get('/:id/children', 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 children = await conceptoService.findChildren(getContext(req), req.params.id);
      res.status(200).json({ success: true, data: children });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /conceptos
   * Crear concepto
   */
  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: CreateConceptoDto = req.body;

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

      // Verificar código único
      const exists = await conceptoService.codeExists(getContext(req), dto.code);
      if (exists) {
        res.status(409).json({ error: 'Conflict', message: 'Concept code already exists' });
        return;
      }

      const concepto = await conceptoService.createConcepto(getContext(req), dto);
      res.status(201).json({ success: true, data: concepto });
    } catch (error) {
      next(error);
    }
  });

  /**
   * PATCH /conceptos/:id
   * Actualizar concepto
   */
  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: UpdateConceptoDto = req.body;
      const concepto = await conceptoService.update(getContext(req), req.params.id, dto);

      if (!concepto) {
        res.status(404).json({ error: 'Not Found', message: 'Concept not found' });
        return;
      }

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

  /**
   * DELETE /conceptos/:id
   * Eliminar concepto (soft delete)
   */
  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;
      }

      const deleted = await conceptoService.softDelete(getContext(req), req.params.id);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Concept not found' });
        return;
      }

      res.status(200).json({ success: true, message: 'Concept deleted' });
    } catch (error) {
      next(error);
    }
  });

  return router;
}

export default createConceptoController;
