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.AddDiscountProductImage;

public class AddDiscountProductImageCommandHandler : IRequestHandler<AddDiscountProductImageCommand, long>
{
    private readonly IApplicationDbContext _context;
    private readonly IFileManager _fileManager;

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

    public async Task<long> Handle(AddDiscountProductImageCommand request, CancellationToken cancellationToken)
    {
        // Verify product exists
        var productExists = await _context.DiscountProducts
            .AnyAsync(p => p.Id == request.DiscountProductId, cancellationToken);
        
        if (!productExists)
            throw new InvalidOperationException($"DiscountProduct with Id {request.DiscountProductId} not found.");

        var imagePath = request.ImagePath;
        var thumbnailPath = request.ThumbnailPath;

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

            imagePath = result.Main.Path;
            thumbnailPath = result.Thumbnail.Path;
        }

        // Get the max sort order for this product
        var maxSortOrder = await _context.DiscountProductImages
            .Where(i => i.DiscountProductId == request.DiscountProductId)
            .MaxAsync(i => (int?)i.SortOrder, cancellationToken) ?? 0;

        var image = new DiscountProductImage
        {
            DiscountProductId = request.DiscountProductId,
            ImagePath = imagePath,
            ThumbnailPath = thumbnailPath,
            Title = request.Title,
            AltText = request.AltText,
            SortOrder = maxSortOrder + 1,
            IsActive = true
        };

        _context.DiscountProductImages.Add(image);
        await _context.SaveChangesAsync(cancellationToken);

        return image.Id;
    }
}
