using DocumentFormat.OpenXml.Packaging;
using Fast.Shared.Logic.ValuationByPath;

namespace Fast.Web.Logic.ReportSources;

class ValuationDataByPath : ReportSourceBase
{
    public ValuationDataByPath(MyDbContext context, SpreadsheetDocument wb, string reportName, int dataSourceId, int filterId, string filterName, List<ReportFilterParameter> filterParams, int userInfoId)
        : base(context, wb, reportName, dataSourceId, filterId, filterName, filterParams, userInfoId) { }

    public override async Task<List<ReportFilterParameter>> Run()
    {
        var valParams = await GetValParams();

        bool hasGasProduct = true;
        var valGas = new PathValuaterGas();
        List<PathValuationResult>? valsGas = new();

        bool hasCrudeProduct = true;
        var valCrude = new PathValuaterCrude();
        List<PathValuationResult>? valsCrude = new();

        string paramName;

        paramName = "Product";
        if (HasParam(paramName))
        {
            await FixInvalidFilterParams(paramName);
            var idList = GetIdList(paramName);
            hasGasProduct = idList.Contains((int)Enums.Product.NaturalGas);
            hasCrudeProduct = idList.Contains((int)Enums.Product.CrudeOil);
        }

        if (hasGasProduct)
            valsGas = await valGas.GetValuationValues(valParams);

        if (hasCrudeProduct)
            valsCrude = await valCrude.GetValuationValues(valParams);

        var vals = valsGas.Concat(valsCrude).ToList();

        paramName = "Counterparty";
        if (HasParam(paramName))
        {
            await FixInvalidFilterParams(paramName);
            var idList = GetIdList(paramName);
            vals = vals.Where(x =>
                (x.ReceiptCounterpartyId != null && idList.Contains(x.ReceiptCounterpartyId.Value))
                || (x.DeliveryCounterpartyId != null && idList.Contains(x.DeliveryCounterpartyId.Value))
            ).ToList();
        }

        paramName = "Pipeline";
        if (HasParam(paramName))
        {
            await FixInvalidFilterParams(paramName);
            var idList = GetIdList(paramName);
            vals = vals.Where(x => idList.Contains(x.ReceiptPipeId) || idList.Contains(x.DeliveryPipeId)).ToList();
        }

        paramName = "Meter";
        if (HasParam(paramName))
        {
            await FixInvalidFilterParams(paramName);
            var idList = GetIdList(paramName);
            vals = vals.Where(x => idList.Contains(x.ReceiptMeterId) || idList.Contains(x.DeliveryMeterId)).ToList();
        }

        if (vals.Count == 0)
            return GetNewFilterParams();

        FillSheet("Valuation Data by Path", vals);

        return GetNewFilterParams();
    }
}
