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

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.RemoveFromCustomerCart;

public class RemoveFromCustomerCartCommandHandler : IRequestHandler<RemoveFromCustomerCartCommand, RemoveFromCustomerCartCommandResponse>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

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

    public async Task<RemoveFromCustomerCartCommandResponse> Handle(RemoveFromCustomerCartCommand 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 and remove cart item
        var cartItem = await _context.UserCarts
            .FirstOrDefaultAsync(uc => uc.Id == request.CartItemId && uc.UserId == userId, cancellationToken);

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

        _context.UserCarts.Remove(cartItem);
        await _context.SaveChangesAsync(cancellationToken);

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