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

namespace Indotalent.Shared.Utils;

public static class SalesQuotationHelper
{
    public static void Recalculate(AppDbContext context, string quotationId)
    {
        var quotation = context.SalesQuotation
            .Include(x => x.Tax)
            .SingleOrDefault(x => x.Id == quotationId);

        if (quotation == null) return;

        var items = context.SalesQuotationItem
            .Where(x => x.SalesQuotationId == quotationId)
            .ToList();

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

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

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

        context.SalesQuotation.Update(quotation);
        context.SaveChanges();
    }
}