/**
 * CostCenterController - Controller de Centros de Costo
 *
 * Endpoints REST para gestión de centros de costo jerárquicos.
 *
 * @module Admin
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { CostCenterService, CreateCostCenterDto, UpdateCostCenterDto, CostCenterFilters } from '../services/cost-center.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { CostCenter } from '../entities/cost-center.entity';
import { User } from '../../core/entities/user.entity';
import { Tenant } from '../../core/entities/tenant.entity';
import { RefreshToken } from '../../auth/entities/refresh-token.entity';

interface ServiceContext {
  tenantId: string;
  userId?: string;
}

export function createCostCenterController(dataSource: DataSource): Router {
  const router = Router();

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

  // Servicios
  const costCenterService = new CostCenterService(costCenterRepository);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

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

  /**
   * GET /cost-centers
   */
  router.get('/', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.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 filters: CostCenterFilters = {};
      if (req.query.costCenterType) filters.costCenterType = req.query.costCenterType as any;
      if (req.query.level) filters.level = req.query.level as any;
      if (req.query.fraccionamientoId) filters.fraccionamientoId = req.query.fraccionamientoId as string;
      if (req.query.parentId) filters.parentId = req.query.parentId as string;
      if (req.query.responsibleId) filters.responsibleId = req.query.responsibleId as string;
      if (req.query.isActive !== undefined) filters.isActive = req.query.isActive === 'true';
      if (req.query.search) filters.search = req.query.search as string;

      const result = await costCenterService.findWithFilters(getContext(req), filters, 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 /cost-centers/tree
   */
  router.get('/tree', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const fraccionamientoId = req.query.fraccionamientoId as string | undefined;
      const tree = await costCenterService.getTree(getContext(req), fraccionamientoId);

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

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

      const stats = await costCenterService.getStats(getContext(req));
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

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

      const fraccionamientoId = req.query.fraccionamientoId as string | undefined;
      const summary = await costCenterService.getBudgetSummary(getContext(req), fraccionamientoId);

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

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

      const cc = await costCenterService.findByCode(getContext(req), req.params.code);
      if (!cc) {
        res.status(404).json({ error: 'Not Found', message: 'Cost center not found' });
        return;
      }

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

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

      const cc = await costCenterService.findById(getContext(req), req.params.id);
      if (!cc) {
        res.status(404).json({ error: 'Not Found', message: 'Cost center not found' });
        return;
      }

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

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

      const children = await costCenterService.getChildren(getContext(req), req.params.id);
      res.status(200).json({ success: true, data: children });
    } catch (error) {
      next(error);
    }
  });

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

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

      const cc = await costCenterService.createCostCenter(getContext(req), dto);
      res.status(201).json({ success: true, data: cc });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message.includes('already exists')) {
          res.status(409).json({ error: 'Conflict', message: error.message });
          return;
        }
        if (error.message.includes('not found')) {
          res.status(400).json({ error: 'Bad Request', message: error.message });
          return;
        }
      }
      next(error);
    }
  });

  /**
   * PUT /cost-centers/:id
   */
  router.put('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'finance'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const dto: UpdateCostCenterDto = req.body;
      const cc = await costCenterService.update(getContext(req), req.params.id, dto);

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

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

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

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

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

  return router;
}

export default createCostCenterController;
