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

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.UpdateDiscountProduct;

public class UpdateDiscountProductCommandHandler : IRequestHandler<UpdateDiscountProductCommand, Unit>
{
    private readonly IApplicationDbContext _context;
    private readonly IFileManager _fileManager;

    public UpdateDiscountProductCommandHandler(IApplicationDbContext context, IFileManager fileManager)
    {
        _context = context;
        _fileManager = fileManager;
    }

    public async Task<Unit> Handle(UpdateDiscountProductCommand request, CancellationToken cancellationToken)
    {
        var product = await _context.DiscountProducts
            .FirstOrDefaultAsync(p => p.Id == request.ProductId, cancellationToken);

        if (product == null)
            throw new Exception("محصول یافت نشد");

        product.Title = request.Title;
        product.ShortInfomation = request.ShortInfomation;
        product.FullInformation = request.FullInformation;
        product.Price = request.Price;
        product.MaxDiscountPercent = request.MaxDiscountPercent;
        product.RemainingCount = request.RemainingCount;
        product.IsActive = request.IsActive;

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

            product.ImagePath = result.Main.Path;
            product.ThumbnailPath = result.Thumbnail.Path;
        }
        else if (!string.IsNullOrEmpty(request.ImagePath))
        {
            product.ImagePath = request.ImagePath;
        }

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

            product.ThumbnailPath = thumbResult.Path;
        }
        else if (!string.IsNullOrEmpty(request.ThumbnailPath))
        {
            product.ThumbnailPath = request.ThumbnailPath;
        }

        // Update categories
        var existingCategories = await _context.DiscountProductCategories
            .Where(pc => pc.ProductId == request.ProductId)
            .ToListAsync(cancellationToken);

        _context.DiscountProductCategories.RemoveRange(existingCategories);

        if (request.CategoryIds.Any())
        {
            var newCategories = request.CategoryIds.Select(categoryId => new DiscountProductCategory
            {
                ProductId = product.Id,
                CategoryId = categoryId
            }).ToList();

            _context.DiscountProductCategories.AddRange(newCategories);
        }

        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
