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

namespace CMSMicroservice.Application.ProductsCQ.Commands.UpdateProductBulk;

public class UpdateProductBulkCommandHandler : IRequestHandler<UpdateProductBulkCommand, UpdateProductBulkResponseDto>
{
    private readonly IApplicationDbContext _context;
    private readonly ILogger<UpdateProductBulkCommandHandler> _logger;

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

    public async Task<UpdateProductBulkResponseDto> Handle(UpdateProductBulkCommand request, CancellationToken cancellationToken)
    {
        var response = new UpdateProductBulkResponseDto
        {
            TotalRequested = request.ProductIds.Count
        };

        var products = await _context.Products
            .Where(x => request.ProductIds.Contains(x.Id) && !x.IsDeleted)
            .ToListAsync(cancellationToken);

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

        foreach (var product in products)
        {
            try
            {
                // تغییر قیمت
                if (request.NewPrice.HasValue)
                {
                    product.Price = request.NewPrice.Value;
                }
                else if (request.PriceChangePercent.HasValue)
                {
                    var changeAmount = (long)(product.Price * (request.PriceChangePercent.Value / 100));
                    product.Price += changeAmount;
                    
                    // اطمینان از مثبت بودن قیمت
                    if (product.Price < 0)
                        product.Price = 0;
                }

                // تغییر موجودی
                if (request.Stock.HasValue)
                {
                    product.RemainingCount = request.Stock.Value;
                }
                else if (request.StockIncrement.HasValue)
                {
                    product.RemainingCount += request.StockIncrement.Value;
                    
                    // اطمینان از غیرمنفی بودن موجودی
                    if (product.RemainingCount < 0)
                        product.RemainingCount = 0;
                }

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

        await _context.SaveChangesAsync(cancellationToken);

        _logger.LogInformation(
            "Bulk update completed. Success: {Success}, Failed: {Failed}",
            response.SuccessCount,
            response.FailedCount
        );

        return response;
    }
}
