using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.UpdateCustomerCartItem;

public class UpdateCustomerCartItemCommandHandler : IRequestHandler<UpdateCustomerCartItemCommand, UpdateCustomerCartItemCommandResponse>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

    public UpdateCustomerCartItemCommandHandler(IApplicationDbContext context, ICurrentUserService currentUser)
    {
        _context = context;
        _currentUser = currentUser;
    }

    public async Task<UpdateCustomerCartItemCommandResponse> Handle(UpdateCustomerCartItemCommand request, CancellationToken cancellationToken)
    {
        // Extract UserId from JWT token
        var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
        if (userId == 0)
        {
            throw new UnauthorizedAccessException("User not authenticated");
        }

        // Find cart item
        var cartItem = await _context.UserCarts
            .FirstOrDefaultAsync(uc => uc.Id == request.CartItemId && uc.UserId == userId, cancellationToken);

        if (cartItem == null)
        {
            return new UpdateCustomerCartItemCommandResponse
            {
                Success = false,
                Message = "آیتم سبد خرید یافت نشد"
            };
        }

        // Update count
        if (request.Count <= 0)
        {
            // Remove item if count is 0 or negative
            _context.UserCarts.Remove(cartItem);
            await _context.SaveChangesAsync(cancellationToken);

            return new UpdateCustomerCartItemCommandResponse
            {
                Success = true,
                Message = "آیتم از سبد خرید حذف شد"
            };
        }

        cartItem.Count = request.Count;
        _context.UserCarts.Update(cartItem);
        await _context.SaveChangesAsync(cancellationToken);

        return new UpdateCustomerCartItemCommandResponse
        {
            Success = true,
            Message = "تعداد آیتم به‌روزرسانی شد"
        };
    }
}
