"use strict";
/**
 * ConsumoObraController - Controller de consumos de materiales
 *
 * Endpoints REST para registro de consumos de materiales por obra.
 *
 * @module Inventory
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.createConsumoObraController = createConsumoObraController;
const express_1 = require("express");
const consumo_obra_service_1 = require("../services/consumo-obra.service");
const auth_middleware_1 = require("../../auth/middleware/auth.middleware");
const auth_service_1 = require("../../auth/services/auth.service");
const consumo_obra_entity_1 = require("../entities/consumo-obra.entity");
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");
/**
 * Crear router de consumos
 */
function createConsumoObraController(dataSource) {
    const router = (0, express_1.Router)();
    // Repositorios
    const consumoRepository = dataSource.getRepository(consumo_obra_entity_1.ConsumoObra);
    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);
    // Servicios
    const consumoService = new consumo_obra_service_1.ConsumoObraService(consumoRepository);
    const authService = new auth_service_1.AuthService(userRepository, tenantRepository, refreshTokenRepository);
    const authMiddleware = new auth_middleware_1.AuthMiddleware(authService, dataSource);
    // Helper para crear contexto de servicio
    const getContext = (req) => {
        if (!req.tenantId) {
            throw new Error('Tenant ID is required');
        }
        return {
            tenantId: req.tenantId,
            userId: req.user?.sub,
        };
    };
    /**
     * GET /consumos
     * Listar consumos con filtros
     */
    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 page = parseInt(req.query.page) || 1;
            const limit = Math.min(parseInt(req.query.limit) || 20, 100);
            const filters = {
                fraccionamientoId: req.query.fraccionamientoId,
                loteId: req.query.loteId,
                conceptoId: req.query.conceptoId,
                productId: req.query.productId,
                dateFrom: req.query.dateFrom ? new Date(req.query.dateFrom) : undefined,
                dateTo: req.query.dateTo ? new Date(req.query.dateTo) : undefined,
            };
            const result = await consumoService.findWithFilters(getContext(req), filters, page, limit);
            res.status(200).json({
                success: true,
                data: result.data,
                pagination: result.meta,
            });
        }
        catch (error) {
            next(error);
        }
    });
    /**
     * GET /consumos/stats/:fraccionamientoId
     * Obtener estadísticas de consumos por fraccionamiento
     */
    router.get('/stats/:fraccionamientoId', 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 stats = await consumoService.getStats(getContext(req), req.params.fraccionamientoId);
            res.status(200).json({ success: true, data: stats });
        }
        catch (error) {
            next(error);
        }
    });
    /**
     * GET /consumos/:id
     * Obtener consumo por 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 consumo = await consumoService.findById(getContext(req), req.params.id);
            if (!consumo) {
                res.status(404).json({ error: 'Not Found', message: 'Consumption record not found' });
                return;
            }
            res.status(200).json({ success: true, data: consumo });
        }
        catch (error) {
            next(error);
        }
    });
    /**
     * POST /consumos
     * Registrar consumo de material
     */
    router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', '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 dto = req.body;
            if (!dto.fraccionamientoId || !dto.productId || dto.quantity === undefined || !dto.consumptionDate) {
                res.status(400).json({
                    error: 'Bad Request',
                    message: 'fraccionamientoId, productId, quantity and consumptionDate are required',
                });
                return;
            }
            dto.consumptionDate = new Date(dto.consumptionDate);
            const consumo = await consumoService.create(getContext(req), dto);
            res.status(201).json({ success: true, data: consumo });
        }
        catch (error) {
            next(error);
        }
    });
    /**
     * DELETE /consumos/:id
     * Eliminar registro de consumo (soft delete)
     */
    router.delete('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer'), 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 consumoService.softDelete(getContext(req), req.params.id);
            if (!deleted) {
                res.status(404).json({ error: 'Not Found', message: 'Consumption record not found' });
                return;
            }
            res.status(200).json({ success: true, message: 'Consumption record deleted' });
        }
        catch (error) {
            next(error);
        }
    });
    return router;
}
exports.default = createConsumoObraController;
//# sourceMappingURL=consumo-obra.controller.js.map