using PropertyFuzeData;

namespace EfformanceBilling
{
    public class EfformanceBilling
    {
        public List<InvoiceDetail> GetSubscriptionInvoiceDetails(int ClientID, int InvoicePropertyID, int AccountID, DateOnly AsOfDate, List<RecurringCharge> recurringCharges)
        {
            List<InvoiceDetail> rtn = new List<InvoiceDetail>();

            List<RecurringCharge> recurringChargesForClient = (
                from rc in recurringCharges 
                where rc.EntityKeyID == AccountID
                select rc).ToList();

            if (recurringCharges is null) { return new List<InvoiceDetail>(); }

            // All these date variables will be used to prorate the recurring charge
            // amount if the recurring charge starts and/or ends in the middle of the month.
            int daysInMonth = DateTime.DaysInMonth(AsOfDate.Year, AsOfDate.Month);
            int dayYear = AsOfDate.Year;
            int dayMonth = AsOfDate.Month;

            DateTime firstDateOfMonth = new DateTime(dayYear, dayMonth, 1);
            DateTime lastDateOfMonth = new DateTime(dayYear, dayMonth, daysInMonth);

            foreach (RecurringCharge recurringCharge in recurringChargesForClient)
            {
                // In Rent Manager a NULL fromDate means it has no beginning and a NULL
                // endDate means it has no end.
                DateTime fromDate = recurringCharge.FromDate ?? firstDateOfMonth;
                DateTime toDate = recurringCharge.ToDate ?? lastDateOfMonth;

                // Prorate the amount
                decimal invoiceDetailAmount = Math.Round(recurringCharge.Amount * (toDate.Day - fromDate.Day + 1) / daysInMonth, 2);

                rtn.Add(new InvoiceDetail
                {
                    InvoiceDetailID = RentManagerAPIHelper.RMNullValue,
                    InvoiceID = RentManagerAPIHelper.RMNullValue,
                    InventoryItemID = RentManagerAPIHelper.RMNullValue,
                    PropertyID = InvoicePropertyID,
                    UnitID = RentManagerAPIHelper.RMNullValue,
                    AccountID = AccountID,
                    ChargeTypeID = recurringCharge.ChargeTypeID,
                    Comment = recurringCharge.ChargeType.Description,
                    UnitCost = invoiceDetailAmount,
                    Quantity = 1
                });
            }

            return rtn;
        }
    }
}
