using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using Microsoft.Extensions.Logging;

namespace CMSMicroservice.Application.ProductsCQ.Commands.UpdateProducts;

public class UpdateProductsCommandHandler : IRequestHandler<UpdateProductsCommand, Unit>
{
    private readonly IApplicationDbContext _context;
    private readonly IFileManager _fileManager;
    private readonly ILogger<UpdateProductsCommandHandler> _logger;

    public UpdateProductsCommandHandler(
        IApplicationDbContext context,
        IFileManager fileManager,
        ILogger<UpdateProductsCommandHandler> logger)
    {
        _context = context;
        _fileManager = fileManager;
        _logger = logger;
    }

    public async Task<Unit> Handle(UpdateProductsCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.Products
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken)
            ?? throw new NotFoundException(nameof(Product), request.Id);

        // Update basic properties
        entity.Title = request.Title;
        entity.Description = request.Description;
        entity.ShortInfomation = request.ShortInfomation;
        entity.FullInformation = request.FullInformation;
        entity.Price = request.Price;
        entity.Discount = request.Discount;
        entity.Rate = request.Rate;
        entity.SaleCount = request.SaleCount;
        entity.ViewCount = request.ViewCount;
        entity.RemainingCount = request.RemainingCount;

        // آپلود تصویر اصلی جدید (اگر ارسال شده باشد)
        if (request.ImageFileBytes is { Length: > 0 })
        {
            var result = await _fileManager.UploadImageAsync(
                "Images/Products",
                request.ImageFileBytes,
                request.ImageFileMime ?? "image/jpeg",
                request.ImageFileName,
                cancellationToken);

            entity.ImagePath = result.Main.Path;
            entity.ThumbnailPath = result.Thumbnail.Path;
        }

        // آپلود بندانگشتی جداگانه (اختیاری — جایگزین بندانگشتی خودکار)
        if (request.ThumbnailFileBytes is { Length: > 0 })
        {
            var thumbResult = await _fileManager.UploadAsync(
                "Images/Products/Thumbnails",
                request.ThumbnailFileBytes,
                request.ThumbnailFileMime ?? "image/jpeg",
                request.ThumbnailFileName,
                cancellationToken);

            entity.ThumbnailPath = thumbResult.Path;
        }

        _context.Products.Update(entity);
        await _context.SaveChangesAsync(cancellationToken);

        // Update category assignments
        if (request.CategoryIds != null)
        {
            // Remove existing categories
            var existingCategories = await _context.ProductCategories
                .Where(pc => pc.ProductId == entity.Id)
                .ToListAsync(cancellationToken);
            
            _context.ProductCategories.RemoveRange(existingCategories);

            // Add new categories
            foreach (var categoryId in request.CategoryIds)
            {
                var categoryExists = await _context.Categories
                    .AnyAsync(c => c.Id == categoryId, cancellationToken);
                    
                if (categoryExists)
                {
                    await _context.ProductCategories.AddAsync(new ProductCategory
                    {
                        ProductId = entity.Id,
                        CategoryId = categoryId
                    }, cancellationToken);
                }
            }
            await _context.SaveChangesAsync(cancellationToken);
        }

        return Unit.Value;
    }
}
