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

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.AddToCart;

public class AddToCartCommandHandler : IRequestHandler<AddToCartCommand, AddToCartResponseDto>
{
    private readonly IApplicationDbContext _context;

    public AddToCartCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<AddToCartResponseDto> Handle(AddToCartCommand request, CancellationToken cancellationToken)
    {
        // Check if product exists and is active
        var product = await _context.DiscountProducts
            .FirstOrDefaultAsync(p => p.Id == request.ProductId && p.IsActive, cancellationToken);

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

        // Check stock availability
        if (product.RemainingCount < request.Count)
        {
            return new AddToCartResponseDto
            {
                Success = false,
                Message = $"موجودی کافی نیست. موجودی فعلی: {product.RemainingCount}"
            };
        }

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

        if (existingCartItem != null)
        {
            // Update quantity
            var newCount = existingCartItem.Count + request.Count;
            
            if (product.RemainingCount < newCount)
            {
                return new AddToCartResponseDto
                {
                    Success = false,
                    Message = $"موجودی کافی نیست. موجودی فعلی: {product.RemainingCount}"
                };
            }

            existingCartItem.Count = newCount;
            await _context.SaveChangesAsync(cancellationToken);

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

        // Add new item to cart
        var cartItem = new DiscountShoppingCart
        {
            UserId = request.UserId,
            ProductId = request.ProductId,
            Count = request.Count
        };

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

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