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

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.AddToCustomerCart;

public class AddToCustomerCartCommandHandler : IRequestHandler<AddToCustomerCartCommand, AddToCustomerCartCommandResponse>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

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

    public async Task<AddToCustomerCartCommandResponse> Handle(AddToCustomerCartCommand 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");
        }

        // Check if product exists and is not deleted
        var product = await _context.Products
            .FirstOrDefaultAsync(p => p.Id == request.ProductId && !p.IsDeleted, cancellationToken);

        if (product == null)
        {
            return new AddToCustomerCartCommandResponse
            {
                Success = false,
                Message = "محصول یافت نشد یا حذف شده است"
            };
        }

        // Check if item already exists in cart
        var existingCartItem = await _context.UserCarts
            .FirstOrDefaultAsync(uc => uc.UserId == userId && uc.ProductId == request.ProductId, cancellationToken);

        if (existingCartItem != null)
        {
            // Update count
            existingCartItem.Count += request.Count;
            _context.UserCarts.Update(existingCartItem);

            await _context.SaveChangesAsync(cancellationToken);

            return new AddToCustomerCartCommandResponse
            {
                Id = existingCartItem.Id,
                Success = true,
                Message = "تعداد محصول در سبد خرید به‌روزرسانی شد"
            };
        }

        // Create new cart item
        var cartItem = new UserCart
        {
            UserId = userId,
            ProductId = request.ProductId,
            Count = request.Count,
            Created = DateTime.UtcNow
        };

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

        return new AddToCustomerCartCommandResponse
        {
            Id = cartItem.Id,
            Success = true,
            Message = "محصول به سبد خرید اضافه شد"
        };
    }
}
