/**
 * VendorController - Controller de Proveedores
 *
 * Endpoints REST para gestion de proveedores/contratistas.
 *
 * @module Bidding
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { VendorService, CreateVendorDto, UpdateVendorDto, VendorFilters } from '../services/vendor.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { Vendor } from '../entities/vendor.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 createVendorController(dataSource: DataSource): Router {
  const router = Router();

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

  // Servicios
  const vendorService = new VendorService(vendorRepository);
  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 /vendors
   */
  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: VendorFilters = {
        page: parseInt(req.query.page as string) || 1,
        limit: Math.min(parseInt(req.query.limit as string) || 20, 100),
      };

      if (req.query.search) filters.search = req.query.search as string;
      if (req.query.specialty) filters.specialty = req.query.specialty as string;
      if (req.query.isActive !== undefined) filters.isActive = req.query.isActive === 'true';
      if (req.query.minRating) filters.minRating = parseFloat(req.query.minRating as string);

      const result = await vendorService.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 /vendors/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 vendor = await vendorService.findByCode(getContext(req), req.params.code);
      if (!vendor) {
        res.status(404).json({ error: 'Not Found', message: 'Vendor not found' });
        return;
      }

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

  /**
   * GET /vendors/rfc/:rfc
   */
  router.get('/rfc/:rfc', 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 vendor = await vendorService.findByRfc(getContext(req), req.params.rfc);
      if (!vendor) {
        res.status(404).json({ error: 'Not Found', message: 'Vendor not found' });
        return;
      }

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

  /**
   * GET /vendors/:id/performance
   */
  router.get('/:id/performance', 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 performance = await vendorService.getPerformanceHistory(getContext(req), req.params.id);
      res.status(200).json({ success: true, data: performance });
    } catch (error) {
      next(error);
    }
  });

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

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

  /**
   * POST /vendors
   */
  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: CreateVendorDto = req.body;
      if (!dto.companyName) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'companyName is required',
        });
        return;
      }

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

  /**
   * PATCH /vendors/: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: UpdateVendorDto = req.body;
      const vendor = await vendorService.update(getContext(req), req.params.id, dto);

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

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

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

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

  /**
   * PATCH /vendors/:id/rating
   */
  router.patch('/:id/rating', 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 { rating } = req.body;
      if (rating === undefined) {
        res.status(400).json({ error: 'Bad Request', message: 'rating is required' });
        return;
      }

      const vendor = await vendorService.updateRating(getContext(req), req.params.id, rating);

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

  return router;
}

export default createVendorController;
