using Netina.Common.Models.Api;
using Netina.Common.Models.Exception;
using Netina.Domain.CommandQueries.Commands;
using Netina.Domain.Entities.Orders;
using Netina.Domain.Enums;
using Netina.Repository.Repositories.Base.Contracts;

namespace Netina.Core.EntityServices.OrderHandlers;

public class ConfirmOrderStepCommandHandler : IRequestHandler<ConfirmOrderStepCommand, bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public ConfirmOrderStepCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(ConfirmOrderStepCommand request, CancellationToken cancellationToken)
    {
        var order = await _repositoryWrapper.SetRepository<Order>()
            .TableNoTracking
            .FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);
        if (order == null)
            throw new AppException("Order not found", ApiResultStatusCode.NotFound);

        order.SetOrderStatus(request.NextOrderStatus);

        if (request.NextOrderStatus == OrderStatus.Delivered)
        {
            var delivery = await _repositoryWrapper.SetRepository<OrderDelivery>()
                .TableNoTracking
                .FirstOrDefaultAsync(od => od.OrderId == order.Id, cancellationToken);
            if (delivery != null)
            {
                if (request.TrackingCode == null || request.TrackingCode.IsNullOrEmpty())
                    throw new AppException("لطفا کد پیگیری ارسال را پر کنید");
                delivery.SetTrackingCode(request.TrackingCode);
                _repositoryWrapper.SetRepository<OrderDelivery>()
                    .Update(delivery);
                await _repositoryWrapper.SaveChangesAsync(cancellationToken);
            }
        }

        _repositoryWrapper.SetRepository<Order>()
            .Update(order);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);

        return true;
    }
}