using CashLineERP.Contracts.Procurement;

namespace CashLineERP.Application.Procurement;

public sealed class PurchaseOrderService : IPurchaseOrderService
{
    private readonly IPurchaseOrderRepository _repository;

    public PurchaseOrderService(IPurchaseOrderRepository repository)
    {
        _repository = repository;
    }

    public IReadOnlyCollection<PurchaseOrderResponse> GetPurchaseOrders() =>
        _repository.GetPurchaseOrders().Select(Map).ToArray();

    public PurchaseOrderResponse? GetPurchaseOrder(long purchaseOrderId)
    {
        var purchaseOrder = _repository.GetPurchaseOrder(purchaseOrderId);
        return purchaseOrder is null ? null : Map(purchaseOrder);
    }

    private static PurchaseOrderResponse Map(PurchaseOrderDetailView purchaseOrder) =>
        new(
            purchaseOrder.PurchaseOrderId,
            purchaseOrder.PurchaseOrderNumber,
            purchaseOrder.BranchId,
            purchaseOrder.SupplierId,
            purchaseOrder.PurchaseRequisitionId,
            purchaseOrder.PurchaseOrderDate,
            purchaseOrder.CurrencyCode,
            purchaseOrder.ExchangeRate,
            purchaseOrder.StatusCode,
            purchaseOrder.SubtotalAmount,
            purchaseOrder.TaxAmount,
            purchaseOrder.TotalAmount,
            purchaseOrder.Lines.Select(line => new PurchaseOrderLineResponse(
                line.PurchaseOrderLineId,
                line.LineNumber,
                line.ItemId,
                line.WarehouseId,
                line.OrderedQuantity,
                line.ReceivedQuantity,
                line.UnitOfMeasureCode,
                line.UnitPrice,
                line.TaxCode,
                line.LineNetAmount,
                line.LineTaxAmount,
                line.LineTotalAmount)).ToArray());
}
