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

namespace Indotalent.Shared.Utils;

public static class SalesOrderHelper
{
    public static void Recalculate(AppDbContext context, string salesOrderId)
    {
        var salesOrder = context.SalesOrder
            .Include(x => x.Tax)
            .SingleOrDefault(x => x.Id == salesOrderId);

        if (salesOrder == null)
            return;

        var salesOrderItems = context.SalesOrderItem
            .Where(x => x.SalesOrderId == salesOrderId)
            .ToList();

        salesOrder.BeforeTaxAmount = salesOrderItems.Sum(x => x.Total ?? 0m);

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

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

        context.SalesOrder.Update(salesOrder);
        context.SaveChanges();
    }
}