namespace CMSMicroservice.Application.ProductsCQ.Commands.ToggleProductStatus;

public class ToggleProductStatusCommandHandler : IRequestHandler<ToggleProductStatusCommand, ToggleProductStatusResponseDto>
{
    private readonly IApplicationDbContext _context;
    private readonly ILogger<ToggleProductStatusCommandHandler> _logger;

    public ToggleProductStatusCommandHandler(
        IApplicationDbContext context,
        ILogger<ToggleProductStatusCommandHandler> logger)
    {
        _context = context;
        _logger = logger;
    }

    public async Task<ToggleProductStatusResponseDto> Handle(ToggleProductStatusCommand request, CancellationToken cancellationToken)
    {
        var response = new ToggleProductStatusResponseDto();

        // دریافت محصولات از دیتابیس
        var products = await _context.Products
            .Where(p => request.ProductIds.Contains(p.Id))
            .ToListAsync(cancellationToken);

        if (products.Count == 0)
        {
            response.Errors.Add("هیچ محصولی با شناسه‌های داده شده یافت نشد");
            return response;
        }

        foreach (var product in products)
        {
            try
            {
                if (request.Enable)
                {
                    // فعال‌سازی: اگر موجودی 0 است، آن را به مقدار پیش‌فرض تنظیم کن
                    if (product.RemainingCount == 0)
                    {
                        product.RemainingCount = request.DefaultStock;
                        _logger.LogInformation(
                            "Product {ProductId} enabled with stock {Stock}", 
                            product.Id, request.DefaultStock);
                    }
                    else
                    {
                        _logger.LogInformation(
                            "Product {ProductId} already has stock {Stock}, no change needed", 
                            product.Id, product.RemainingCount);
                    }
                }
                else
                {
                    // غیرفعال‌سازی: موجودی را به 0 تنظیم کن
                    var oldStock = product.RemainingCount;
                    product.RemainingCount = 0;
                    _logger.LogInformation(
                        "Product {ProductId} disabled (stock changed from {OldStock} to 0)", 
                        product.Id, oldStock);
                }

                response.UpdatedCount++;
            }
            catch (Exception ex)
            {
                response.FailedCount++;
                response.Errors.Add($"خطا در به‌روزرسانی محصول {product.Id}: {ex.Message}");
                _logger.LogError(ex, "Error toggling product {ProductId} status", product.Id);
            }
        }

        if (response.UpdatedCount > 0)
        {
            await _context.SaveChangesAsync(cancellationToken);
            _logger.LogInformation(
                "Toggle product status completed: {UpdatedCount} succeeded, {FailedCount} failed (Enable: {Enable})", 
                response.UpdatedCount, response.FailedCount, request.Enable);
        }

        return response;
    }
}
