using Microsoft.EntityFrameworkCore;
using NetinaShop.Domain.Entities.Accounting;

namespace NetinaShop.Repository.Handlers.Accounting;

public class GetPaymentQueryHandler : IRequestHandler<GetPaymentQuery,PaymentSDto>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public GetPaymentQueryHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<PaymentSDto> Handle(GetPaymentQuery request, CancellationToken cancellationToken)
    {
        PaymentSDto? payment = null;
        if (request.Authority != null)
        {
             payment = await _repositoryWrapper.SetRepository<Payment>()
                .TableNoTracking
                .Where(p => p.Authority == request.Authority)
                .Select(PaymentMapper.ProjectToSDto)
                .FirstOrDefaultAsync(cancellationToken);
        }
        else
        {
            if (request.Id == default)
                throw new Exception("Id is null");

            payment = await _repositoryWrapper.SetRepository<Payment>()
                .TableNoTracking
                .Where(p => p.Id == request.Id)
                .Select(PaymentMapper.ProjectToSDto)
                .FirstOrDefaultAsync(cancellationToken);
        }

        if (payment == null)
            throw new AppException("Payment not found !", ApiResultStatusCode.NotFound);

        return payment;
    }
}