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

namespace Indotalent.Shared.Utils;

public static class PurchaseOrderHelper
{
    public static void Recalculate(AppDbContext context, string purchaseOrderId)
    {
        var purchaseOrder = context.PurchaseOrder
            .Include(x => x.Tax)
            .SingleOrDefault(x => x.Id == purchaseOrderId);

        if (purchaseOrder == null)
            return;

        var purchaseOrderItems = context.PurchaseOrderItem
            .Where(x => x.PurchaseOrderId == purchaseOrderId)
            .ToList();

        purchaseOrder.BeforeTaxAmount = purchaseOrderItems.Sum(x => (x.UnitPrice ?? 0) * (decimal)(x.Quantity ?? 0));

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

        purchaseOrder.AfterTaxAmount = (purchaseOrder.BeforeTaxAmount ?? 0) + (purchaseOrder.TaxAmount ?? 0);

        context.PurchaseOrder.Update(purchaseOrder);
        context.SaveChanges();
    }
}