/**
 * ProposalController - Controller de Propuestas de Proveedores
 *
 * Endpoints REST para gestion de propuestas recibidas de proveedores.
 *
 * @module Bidding
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { ProposalService, CreateProposalDto, UpdateProposalDto, ProposalFilters, EvaluateProposalDto } from '../services/proposal.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { Proposal, ProposalStatus } from '../entities/proposal.entity';
import { Tender } from '../entities/tender.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 createProposalController(dataSource: DataSource): Router {
  const router = Router();

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

  // Servicios
  const proposalService = new ProposalService(proposalRepository, tenderRepository);
  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 /proposals
   */
  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: ProposalFilters = {
        page: parseInt(req.query.page as string) || 1,
        limit: Math.min(parseInt(req.query.limit as string) || 20, 100),
      };

      if (req.query.tenderId) filters.tenderId = req.query.tenderId as string;
      if (req.query.vendorId) filters.vendorId = req.query.vendorId as string;
      if (req.query.status) {
        const statuses = (req.query.status as string).split(',') as ProposalStatus[];
        filters.status = statuses.length === 1 ? statuses[0] : statuses;
      }
      if (req.query.search) filters.search = req.query.search as string;

      const result = await proposalService.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 /proposals/compare/:tenderId
   */
  router.get('/compare/:tenderId', 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 comparison = await proposalService.compareProposals(getContext(req), req.params.tenderId);
      res.status(200).json({ success: true, data: comparison });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /proposals/tender/:tenderId
   */
  router.get('/tender/:tenderId', 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 proposals = await proposalService.findByTender(getContext(req), req.params.tenderId);
      res.status(200).json({ success: true, data: proposals });
    } catch (error) {
      next(error);
    }
  });

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

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

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

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

  /**
   * PATCH /proposals/:id
   */
  router.patch('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'gerente', 'compras'), 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: UpdateProposalDto = req.body;
      const proposal = await proposalService.update(getContext(req), req.params.id, dto);

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

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

  /**
   * POST /proposals/:id/evaluate
   */
  router.post('/:id/evaluate', 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 { technicalScore, economicScore } = req.body;
      if (technicalScore === undefined || economicScore === undefined) {
        res.status(400).json({ error: 'Bad Request', message: 'technicalScore and economicScore are required' });
        return;
      }

      const dto: EvaluateProposalDto = { technicalScore, economicScore };
      const proposal = await proposalService.evaluate(getContext(req), req.params.id, dto);

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

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

      const proposal = await proposalService.disqualify(getContext(req), req.params.id, reason);

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

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

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

  return router;
}

export default createProposalController;
