using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace Fast.Web.Logic.ReportSources;

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

    public override async Task<List<ReportFilterParameter>> Run()
    {
        var query = (from q in db.VwRptCounterparties select q);
        string paramName;

        paramName = "Counterparty";
        if (HasParam(paramName))
        {
            await FixInvalidFilterParams(paramName);
            var idList = GetIdList(paramName);
            query = query.Where(x => x.CounterpartyId.HasValue && idList.Contains(x.CounterpartyId.Value));
        }

        paramName = "Active/Inactive";
        if (HasParam(paramName))
        {
            var isActiveOnly = GetIsActiveValue(paramName);
            var currentDateOnly = DateOnly.FromDateTime(DateTime.UtcNow);
            if (isActiveOnly)
                query = query.Where(x => !x.InactiveDate.HasValue || x.InactiveDate.Value > currentDateOnly);
            else
                query = query.Where(x => x.InactiveDate.HasValue && x.InactiveDate.Value <= currentDateOnly);
        }

        query = query.OrderBy(x => x.Name).ThenByDescending(x => x.InactiveDate);
        var result = await query.ToListAsync();

        //filter relationship on the client side, after the query has been executed
        paramName = "Relationship";
        if (HasParam(paramName))
        {
            await FixInvalidFilterParams(paramName);
            var idList = GetIdList(paramName);
            result = result.Where(x => x.RelationshipIds != null && x.RelationshipIds.Split(',').Any(y => idList.Contains(int.Parse(y)))).ToList();
        }

        FillSheet("Counterparty Data", result);

        return GetNewFilterParams();
    }
}
