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

namespace CMSMicroservice.Application.ProductsCQ.Commands.AddProductImage;

public class AddProductImageCommandHandler : IRequestHandler<AddProductImageCommand, AddProductImageResponseDto>
{
    private readonly IApplicationDbContext _context;
    private readonly IFileManager _fileManager;
    private readonly ILogger<AddProductImageCommandHandler> _logger;

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

    public async Task<AddProductImageResponseDto> Handle(AddProductImageCommand request,
        CancellationToken cancellationToken)
    {
        // بررسی وجود محصول
        var productExists = await _context.Products
            .AnyAsync(p => p.Id == request.ProductId, cancellationToken);
        if (!productExists)
            throw new NotFoundException(nameof(Product), request.ProductId);

        // بدون فایل تصویر، کاری انجام نمی‌شود
        if (request.ImageFileBytes is not { Length: > 0 })
            throw new FileUploadException("فایل تصویر ارسال نشده است");

        // آپلود تصویر به FMS (اگر خطا بخوره، exception پرتاب می‌شه و entity ذخیره نمیشه)
        var uploaded = await _fileManager.UploadImageAsync(
            "Images/Products/Gallery",
            request.ImageFileBytes,
            request.ImageFileMime ?? "image/jpeg",
            request.ImageFileName,
            cancellationToken);

        // ساخت رکورد تصویر
        var productImage = new ProductImage
        {
            Title = request.Title,
            ImagePath = uploaded.Main.Path,
            ImageThumbnailPath = uploaded.Thumbnail.Path
        };

        await _context.ProductImages.AddAsync(productImage, cancellationToken);
        await _context.SaveChangesAsync(cancellationToken);

        // اتصال تصویر به محصول
        var productGallery = new ProductGallery
        {
            ProductId = request.ProductId,
            ProductImageId = productImage.Id
        };

        await _context.ProductGalleries.AddAsync(productGallery, cancellationToken);
        await _context.SaveChangesAsync(cancellationToken);

        return new AddProductImageResponseDto
        {
            ProductGalleryId = productGallery.Id,
            ProductImageId = productImage.Id,
            Title = productImage.Title,
            ImagePath = productImage.ImagePath,
            ImageThumbnailPath = productImage.ImageThumbnailPath
        };
    }
}
