using Indotalent.Data.Entities;
using Indotalent.Infrastructure.Database;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Shared.Utils;

public static class PurchaseRequisitionHelper
{
    public static void Recalculate(AppDbContext context, string requisitionId)
    {
        var requisition = context.PurchaseRequisition
            .Include(x => x.Tax)
            .SingleOrDefault(x => x.Id == requisitionId);

        if (requisition == null) return;

        var items = context.PurchaseRequisitionItem
            .Where(x => x.PurchaseRequisitionId == requisitionId)
            .ToList();

        requisition.BeforeTaxAmount = items.Sum(x => (x.UnitPrice ?? 0m) * (decimal)(x.Quantity ?? 0.0));

        var taxPercentage = requisition.Tax?.PercentageValue ?? 0;
        requisition.TaxAmount = (requisition.BeforeTaxAmount ?? 0m) * (decimal)taxPercentage / 100m;

        requisition.AfterTaxAmount = (requisition.BeforeTaxAmount ?? 0m) + (requisition.TaxAmount ?? 0m);

        context.PurchaseRequisition.Update(requisition);
        context.SaveChanges();
    }
}