using CashLineERP.Contracts.Finance;

namespace CashLineERP.Application.Finance;

public sealed class BankTransferBatchService : IBankTransferBatchService
{
    private readonly IBankTransferBatchRepository _repository;

    public BankTransferBatchService(IBankTransferBatchRepository repository)
    {
        _repository = repository;
    }

    public IReadOnlyCollection<BankTransferBatchResponse> GetBatches() =>
        _repository.GetBatches().Select(Map).ToArray();

    public BankTransferBatchResponse? GetBatch(long bankTransferBatchId)
    {
        var batch = _repository.GetBatch(bankTransferBatchId);
        return batch is null ? null : Map(batch);
    }

    public BankTransferBatchResponse CreateBatch(CreateBankTransferBatchRequest request) =>
        Map(_repository.Create(new CreateBankTransferBatchCommand(
            request.BankAccountCode,
            request.TransferDate,
            request.CurrencyCode,
            request.AccountsPayablePaymentIds)));

    public BankTransferBatchResponse SubmitBatch(long bankTransferBatchId, long actorUserId) =>
        Map(_repository.Submit(bankTransferBatchId, actorUserId));

    public BankTransferBatchResponse ApproveBatch(long bankTransferBatchId, long actorUserId) =>
        Map(_repository.Approve(bankTransferBatchId, actorUserId));

    public BankTransferBatchResponse PostBatch(long bankTransferBatchId, long actorUserId) =>
        Map(_repository.Post(bankTransferBatchId, actorUserId));

    private static BankTransferBatchResponse Map(BankTransferBatchDetailView batch) =>
        new(
            batch.BankTransferBatchId,
            batch.BatchNumber,
            batch.BankAccountCode,
            batch.TransferDate,
            batch.CurrencyCode,
            batch.StatusCode,
            batch.TotalPaymentCount,
            batch.TotalAmount,
            batch.SubmittedAtUtc,
            batch.SubmittedByUserId,
            batch.ApprovedAtUtc,
            batch.ApprovedByUserId,
            batch.PostedAtUtc,
            batch.PostedByUserId,
            batch.Lines.Select(line => new BankTransferBatchLineResponse(
                line.BankTransferBatchLineId,
                line.AccountsPayablePaymentId,
                line.PaymentNumber,
                line.SupplierId,
                line.AmountAmount)).ToArray());
}
