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

namespace NetinaShop.Repository.Handlers.Accounting;

public class CreateOrUpdatePaymentCommandHandler : IRequestHandler<CreateOrUpdatePaymentCommand, bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public CreateOrUpdatePaymentCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(CreateOrUpdatePaymentCommand request, CancellationToken cancellationToken)
    {
        if (request.Id != null)
        {
            var ent = await _repositoryWrapper.SetRepository<Payment>()
                .TableNoTracking
                .FirstOrDefaultAsync(p => p.Id == request.Id, cancellationToken);
            if (ent == null)
                throw new AppException("Payment not found", ApiResultStatusCode.NotFound);

            var newEnt = Payment.Create(request.FactorNumber, request.Amount, request.Description, request.TransactionCode,
                request.CardPan, request.Authority, request.Type, request.Status, request.OrderId, request.UserId);
            newEnt.Id = ent.Id;

            _repositoryWrapper.SetRepository<Payment>()
                .Update(newEnt);

            await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        }
        else
        {
            var orderPayment = await _repositoryWrapper.SetRepository<Payment>()
                .TableNoTracking
                .FirstOrDefaultAsync(p => p.OrderId == request.OrderId && p.Type == request.Type,cancellationToken);
            if (orderPayment != null)
            {
                var newEnt = Payment.Create(request.FactorNumber, request.Amount, request.Description, request.TransactionCode,
                    request.CardPan, request.Authority, request.Type, request.Status, request.OrderId, request.UserId);
                newEnt.Id = orderPayment.Id;

                _repositoryWrapper.SetRepository<Payment>()
                    .Update(newEnt);

                await _repositoryWrapper.SaveChangesAsync(cancellationToken);
            }
            else
            {
                var payment = Payment.Create(request.FactorNumber, request.Amount, request.Description, request.TransactionCode,
                    request.CardPan, request.Authority, request.Type, request.Status, request.OrderId, request.UserId);

                _repositoryWrapper.SetRepository<Payment>()
                    .Add(payment);

                await _repositoryWrapper.SaveChangesAsync(cancellationToken);
            }
        }
        return true;
    }
}