/**
 * BidBudgetController - Controller de Presupuestos de Licitación
 *
 * Endpoints REST para gestión de propuestas económicas.
 *
 * @module Bidding
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { BidBudgetService, CreateBudgetItemDto, UpdateBudgetItemDto, BudgetFilters } from '../services/bid-budget.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { BidBudget } from '../entities/bid-budget.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';

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

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

  // Servicios
  const budgetService = new BidBudgetService(budgetRepository);
  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 /bid-budgets
   */
  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 bidId = req.query.bidId as string;
      if (!bidId) {
        res.status(400).json({ error: 'Bad Request', message: 'bidId is required' });
        return;
      }

      const page = parseInt(req.query.page as string) || 1;
      const limit = Math.min(parseInt(req.query.limit as string) || 100, 500);

      const filters: BudgetFilters = { bidId };
      if (req.query.itemType) filters.itemType = req.query.itemType as any;
      if (req.query.status) filters.status = req.query.status as any;
      if (req.query.parentId !== undefined) {
        filters.parentId = req.query.parentId === 'null' ? null : req.query.parentId as string;
      }
      if (req.query.isSummary !== undefined) filters.isSummary = req.query.isSummary === 'true';

      const result = await budgetService.findWithFilters(getContext(req), filters, page, limit);

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

  /**
   * GET /bid-budgets/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 bidId = req.query.bidId as string;
      if (!bidId) {
        res.status(400).json({ error: 'Bad Request', message: 'bidId is required' });
        return;
      }

      const tree = await budgetService.getTree(getContext(req), bidId);
      res.status(200).json({ success: true, data: tree });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /bid-budgets/summary
   */
  router.get('/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 bidId = req.query.bidId as string;
      if (!bidId) {
        res.status(400).json({ error: 'Bad Request', message: 'bidId is required' });
        return;
      }

      const summary = await budgetService.getSummary(getContext(req), bidId);
      res.status(200).json({ success: true, data: summary });
    } catch (error) {
      next(error);
    }
  });

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

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

  /**
   * POST /bid-budgets
   */
  router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'gerente', 'costos'), 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: CreateBudgetItemDto = req.body;
      if (!dto.bidId || !dto.code || !dto.name || !dto.itemType) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'bidId, code, name, and itemType are required',
        });
        return;
      }

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

  /**
   * PUT /bid-budgets/:id
   */
  router.put('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'gerente', 'costos'), 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: UpdateBudgetItemDto = req.body;
      const item = await budgetService.update(getContext(req), req.params.id, dto);

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

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

  /**
   * POST /bid-budgets/status
   */
  router.post('/status', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'gerente'), 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 { bidId, status } = req.body;
      if (!bidId || !status) {
        res.status(400).json({ error: 'Bad Request', message: 'bidId and status are required' });
        return;
      }

      const updated = await budgetService.changeStatus(getContext(req), bidId, status);
      res.status(200).json({
        success: true,
        message: `Updated ${updated} budget items`,
        data: { updated },
      });
    } catch (error) {
      next(error);
    }
  });

  /**
   * DELETE /bid-budgets/:id
   */
  router.delete('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'gerente'), 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 budgetService.softDelete(getContext(req), req.params.id);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Budget item not found' });
        return;
      }

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

  return router;
}

export default createBidBudgetController;
