/**
 * SubcontractorController - REST API for subcontractors
 *
 * Endpoints para gestión de subcontratistas.
 *
 * @module Contracts
 * @routes /api/subcontractors
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { SubcontractorService, SubcontractorFilters } from '../services/subcontractor.service';
import { Subcontractor } from '../entities/subcontractor.entity';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
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 createSubcontractorController(dataSource: DataSource): Router {
  const router = Router();

  // Repositories
  const subcontractorRepo = dataSource.getRepository(Subcontractor);
  const userRepository = dataSource.getRepository(User);
  const tenantRepository = dataSource.getRepository(Tenant);
  const refreshTokenRepository = dataSource.getRepository(RefreshToken);

  // Services
  const service = new SubcontractorService(subcontractorRepo);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

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

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

      const filters: SubcontractorFilters = {};
      if (req.query.specialty) filters.specialty = req.query.specialty as SubcontractorFilters['specialty'];
      if (req.query.status) filters.status = req.query.status as SubcontractorFilters['status'];
      if (req.query.search) filters.search = req.query.search as string;
      if (req.query.minRating) filters.minRating = parseFloat(req.query.minRating as string);

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

      const result = await service.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 } });
    } catch (error) {
      next(error);
    }
  });

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

      const subcontractors = await service.getBySpecialty(getContext(req), req.params.specialty as any);
      res.status(200).json({ success: true, data: subcontractors });
    } catch (error) {
      next(error);
    }
  });

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

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

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

  /**
   * POST /api/subcontractors
   * Create new subcontractor
   */
  router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'contracts'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

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

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

      const subcontractor = await service.update(getContext(req), req.params.id, req.body);
      if (!subcontractor) {
        res.status(404).json({ error: 'Not Found', message: 'Subcontractor not found' });
        return;
      }

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

  /**
   * POST /api/subcontractors/:id/rate
   * Rate subcontractor
   */
  router.post('/:id/rate', authMiddleware.authenticate, authMiddleware.authorize('admin', 'contracts', 'resident'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const subcontractor = await service.updateRating(getContext(req), req.params.id, req.body.rating);
      if (!subcontractor) {
        res.status(404).json({ error: 'Not Found', message: 'Subcontractor not found' });
        return;
      }

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

  /**
   * POST /api/subcontractors/:id/deactivate
   * Deactivate subcontractor
   */
  router.post('/:id/deactivate', authMiddleware.authenticate, authMiddleware.authorize('admin', 'contracts'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const subcontractor = await service.deactivate(getContext(req), req.params.id);
      if (!subcontractor) {
        res.status(404).json({ error: 'Not Found', message: 'Subcontractor not found' });
        return;
      }

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

  /**
   * POST /api/subcontractors/:id/blacklist
   * Blacklist subcontractor
   */
  router.post('/:id/blacklist', authMiddleware.authenticate, authMiddleware.authorize('admin'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const subcontractor = await service.blacklist(getContext(req), req.params.id, req.body.reason);
      if (!subcontractor) {
        res.status(404).json({ error: 'Not Found', message: 'Subcontractor not found' });
        return;
      }

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

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

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

      res.status(204).send();
    } catch (error) {
      next(error);
    }
  });

  return router;
}
