import fuelRequestModel from "../fuel-requests/fuelRequest.model";
import externalInvoiceModel from "../external-invoices/externalInvoice.model";
import lpgModel from "../lpg/lpg.model";
import approvalModel from "../approvals/approval.model";
import anomalyModel from "../anomalies/anomaly.model";
import pumpReadingModel from "../pump-reading/pumpReading.model";

export class DashboardService {

    async getDashboard(){

        //Total de requisiciones
        const fuelRequests = await fuelRequestModel.countDocuments();

        //Requisiciones pendientes
        const pendingRequests = await fuelRequestModel.countDocuments({

            status:"PENDIENTE"

        });

        const approvedRequests = await fuelRequestModel.countDocuments({

            status:"APROBADO"
            
        });

        const rejectedRequests = await fuelRequestModel.countDocuments({

            status:"RECHAZADO"
            
        });

        //Total de facturas externas
        const externalInvoices = await externalInvoiceModel.countDocuments();

        //Total de requisiciones LPG
        const lpgRequests = await lpgModel.countDocuments();

        //Total de galones solicitados
        const pendingApprovals = await approvalModel.countDocuments({
            status:"PENDIENTE"
        });

        //Total de anomalías abiertas
        const openAnomalies = await anomalyModel.countDocuments({
            status:"ABIERTA"
        })

        //Tootal de lecturas de bomba
        const pumpReadings = await pumpReadingModel.countDocuments();  
        
        const gallons = await fuelRequestModel.aggregate([
                    {
                        $group:{
                            _id:null,
                            totalGallons:{
                                $sum: "$gallonQuantity"
                            }
                        }
                    }
                ]);
        
        //Total invertido
        const totalCost = await fuelRequestModel.aggregate([
                    {
                        $group:{
                            _id:null,
                            totalAmount:{
                                $sum: "$totalAmount"
                            }
                        }
                        
                    }
                ]);
        
        return{
            fuelRequests,
            externalInvoices,
            lpgRequests,
            pendingApprovals,
            openAnomalies,
            pumpReadings,
        
            totalGallons:
                gallons.length > 0
                ? gallons[0].totalGallons
                :0,
        
                    
            totalCost:
                totalCost.length > 0
                ? totalCost[0].totalAmount
                :0
        }
    }
}