namespace Netina.Core.EntityServices.DiscountHandlers;

public class CheckUserDiscountFirstUseCommandHandler(
    IRepositoryWrapper repositoryWrapper,
    ICurrentUserService currentUserService)
    : IRequestHandler<CheckUserDiscountFirstUseCommand, bool>
{
    public async Task<bool> Handle(CheckUserDiscountFirstUseCommand request, CancellationToken cancellationToken)
    {

        if (currentUserService.UserId != null && Guid.TryParse(currentUserService.UserId, out Guid userId))
        {
            var customer = await repositoryWrapper.SetRepository<Customer>()
                .TableNoTracking
                .FirstOrDefaultAsync(c => c.UserId == userId, cancellationToken);
            if (customer == null)
                throw new BaseApiException(ApiResultStatusCode.NotFound, "Customer not found");

            var discountedUserOrder = await repositoryWrapper.SetRepository<Order>()
                .TableNoTracking
                .FirstOrDefaultAsync(f => f.CustomerId == customer.Id && f.DiscountCode == request.DiscountCode,
                    cancellationToken);
            if (discountedUserOrder != null)
                return false;
            return true;
        }
        else
            throw new BaseApiException(ApiResultStatusCode.BadRequest,"UserId is wrong");
    }
}