using ERPCore.Domain.Entities;
using ERPCore.Dtos.Sales;
using ERPCore.Services.Interfaces;

namespace ERPCore.Services;

public sealed class SalesMappingService : ISalesMappingService
{
    public SalesInvoiceTotalsDto MapInvoiceTotals(SalesInvoice invoice)
        => new(
            invoice.Subtotal,
            invoice.DiscountTotal,
            invoice.Lines.Sum(l => l.FreeQty),
            invoice.TaxTotal,
            invoice.GrandTotal,
            invoice.RoundOff,
            invoice.NetPayable,
            invoice.PaidAmount,
            invoice.BalanceAmount);

    public SalesSlipTotalsDto MapSlipTotals(SalesSlip slip)
        => new(
            slip.Subtotal,
            slip.DiscountTotal,
            slip.Lines.Sum(l => l.FreeQty),
            slip.TaxTotal,
            slip.GrandTotal,
            slip.PaidAmount,
            slip.BalanceAmount);

    public SalesInvoiceDto MapInvoice(SalesInvoice invoice)
        => new(
            invoice.SalesInvoiceId, invoice.InvoiceNo, invoice.InvoiceDate, invoice.CustomerId,
            invoice.CustomerSnapshotName, invoice.CustomerSnapshotTaxNo, invoice.WarehouseId,
            invoice.InvoiceType, invoice.Status, invoice.CreatedBy, invoice.CreatedAt, invoice.UpdatedAt,
            invoice.GlJournalNo, invoice.GlPostedAt,
            MapInvoiceTotals(invoice),
            invoice.Lines.Select(l => new SalesInvoiceLineDto(
                l.SalesInvoiceLineId, l.ItemId, l.Description, l.Qty, l.FreeQty, l.WarehouseId,
                l.UnitPrice, l.BaseCost, l.PriceSource, l.DiscountPct, l.DiscountAmount, l.DiscountMode,
                l.NetUnitPrice, l.LineTotal, l.TaxPct, l.TaxAmount, l.IsFreeIssue, l.ParentLineId)).ToList());

    public SalesSlipDto MapSlip(SalesSlip slip)
        => new(
            slip.SalesSlipId, slip.SlipNo, slip.SlipDate, slip.CustomerId, slip.CustomerSnapshotName,
            slip.WarehouseId, slip.CashierUserId, slip.Status, slip.CreatedAt, slip.UpdatedAt,
            MapSlipTotals(slip),
            slip.Lines.Select(l => new SalesSlipLineDto(
                l.SalesSlipLineId, l.ItemId, l.Description, l.Qty, l.FreeQty, l.WarehouseId,
                l.UnitPrice, l.BaseCost, l.PriceSource, l.DiscountPct, l.DiscountAmount, l.DiscountMode,
                l.NetUnitPrice, l.LineTotal, l.TaxPct, l.TaxAmount, l.IsFreeIssue, l.ParentLineId)).ToList());
}
