/**
 * TenderController - Controller de Licitaciones
 *
 * Endpoints REST para gestion de licitaciones.
 *
 * @module Bidding
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { TenderService, CreateTenderDto, UpdateTenderDto, TenderFilters } from '../services/tender.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { Tender, TenderStatus, TenderType } from '../entities/tender.entity';
import { Opportunity } from '../entities/opportunity.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 createTenderController(dataSource: DataSource): Router {
  const router = Router();

  // Repositorios
  const tenderRepository = dataSource.getRepository(Tender);
  const opportunityRepository = dataSource.getRepository(Opportunity);
  const userRepository = dataSource.getRepository(User);
  const tenantRepository = dataSource.getRepository(Tenant);
  const refreshTokenRepository = dataSource.getRepository(RefreshToken);

  // Servicios
  const tenderService = new TenderService(tenderRepository, opportunityRepository);
  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 /tenders
   */
  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 filters: TenderFilters = {
        page: parseInt(req.query.page as string) || 1,
        limit: Math.min(parseInt(req.query.limit as string) || 20, 100),
      };

      if (req.query.opportunityId) filters.opportunityId = req.query.opportunityId as string;
      if (req.query.type) filters.type = req.query.type as TenderType;
      if (req.query.status) {
        const statuses = (req.query.status as string).split(',') as TenderStatus[];
        filters.status = statuses.length === 1 ? statuses[0] : statuses;
      }
      if (req.query.dateFrom) filters.dateFrom = new Date(req.query.dateFrom as string);
      if (req.query.dateTo) filters.dateTo = new Date(req.query.dateTo as string);
      if (req.query.search) filters.search = req.query.search as string;

      const result = await tenderService.findAll(getContext(req), filters);

      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 /tenders/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 year = req.query.year ? parseInt(req.query.year as string) : undefined;
      const stats = await tenderService.getStats(getContext(req), year);
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /tenders/number/:number
   */
  router.get('/number/:number', 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 tender = await tenderService.findByNumber(getContext(req), req.params.number);
      if (!tender) {
        res.status(404).json({ error: 'Not Found', message: 'Tender not found' });
        return;
      }

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

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

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

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

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

  /**
   * PUT /tenders/:id
   */
  router.put('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'gerente', 'comercial'), 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: UpdateTenderDto = req.body;
      const tender = await tenderService.update(getContext(req), req.params.id, dto);

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

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

  /**
   * PATCH /tenders/:id
   */
  router.patch('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'gerente', 'comercial'), 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: UpdateTenderDto = req.body;
      const tender = await tenderService.update(getContext(req), req.params.id, dto);

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

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

  /**
   * POST /tenders/:id/publish
   */
  router.post('/:id/publish', 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 tender = await tenderService.publish(getContext(req), req.params.id);
      res.status(200).json({ success: true, data: tender });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /tenders/:id/award
   */
  router.post('/:id/award', 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 { proposalId } = req.body;
      if (!proposalId) {
        res.status(400).json({ error: 'Bad Request', message: 'proposalId is required' });
        return;
      }

      const tender = await tenderService.awardWinner(getContext(req), req.params.id, proposalId);
      res.status(200).json({ success: true, data: tender });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /tenders/:id/convert
   */
  router.post('/:id/convert', 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 result = await tenderService.convertToProject(getContext(req), req.params.id);
      res.status(200).json({ success: true, data: result });
    } catch (error) {
      next(error);
    }
  });

  /**
   * DELETE /tenders/: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 tenderService.softDelete(getContext(req), req.params.id);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Tender not found' });
        return;
      }

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

  return router;
}

export default createTenderController;
