"use strict";
/**
 * SubcontractorController - REST API for subcontractors
 *
 * Endpoints para gestión de subcontratistas.
 *
 * @module Contracts
 * @routes /api/subcontractors
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSubcontractorController = createSubcontractorController;
const express_1 = require("express");
const subcontractor_service_1 = require("../services/subcontractor.service");
const subcontractor_entity_1 = require("../entities/subcontractor.entity");
const auth_middleware_1 = require("../../auth/middleware/auth.middleware");
const auth_service_1 = require("../../auth/services/auth.service");
const user_entity_1 = require("../../core/entities/user.entity");
const tenant_entity_1 = require("../../core/entities/tenant.entity");
const refresh_token_entity_1 = require("../../auth/entities/refresh-token.entity");
function createSubcontractorController(dataSource) {
    const router = (0, express_1.Router)();
    // Repositories
    const subcontractorRepo = dataSource.getRepository(subcontractor_entity_1.Subcontractor);
    const userRepository = dataSource.getRepository(user_entity_1.User);
    const tenantRepository = dataSource.getRepository(tenant_entity_1.Tenant);
    const refreshTokenRepository = dataSource.getRepository(refresh_token_entity_1.RefreshToken);
    // Services
    const service = new subcontractor_service_1.SubcontractorService(subcontractorRepo);
    const authService = new auth_service_1.AuthService(userRepository, tenantRepository, refreshTokenRepository);
    const authMiddleware = new auth_middleware_1.AuthMiddleware(authService, dataSource);
    // Helper for service context
    const getContext = (req) => {
        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, res, next) => {
        try {
            const tenantId = req.tenantId;
            if (!tenantId) {
                res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
                return;
            }
            const filters = {};
            if (req.query.specialty)
                filters.specialty = req.query.specialty;
            if (req.query.status)
                filters.status = req.query.status;
            if (req.query.search)
                filters.search = req.query.search;
            if (req.query.minRating)
                filters.minRating = parseFloat(req.query.minRating);
            const page = parseInt(req.query.page) || 1;
            const limit = Math.min(parseInt(req.query.limit) || 20, 100);
            const result = await service.findWithFilters(getContext(req), filters, page, limit);
            res.status(200).json({ success: true, data: result.data, pagination: result.meta });
        }
        catch (error) {
            next(error);
        }
    });
    /**
     * GET /api/subcontractors/specialty/:specialty
     * Get subcontractors by specialty
     */
    router.get('/specialty/:specialty', authMiddleware.authenticate, async (req, res, next) => {
        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);
            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, res, next) => {
        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, res, next) => {
        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, res, next) => {
        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, res, next) => {
        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, res, next) => {
        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, res, next) => {
        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, res, next) => {
        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;
}
//# sourceMappingURL=subcontractor.controller.js.map