using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Content;
using MediatR;

namespace CMSMicroservice.Application.SitePageCQ.Commands.UpdateSitePageSection;

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

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

    public async Task<Unit> Handle(UpdateSitePageSectionCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.SitePageSections.FindAsync(new object[] { request.Id }, cancellationToken);
        if (entity == null || entity.IsDeleted)
            throw new NotFoundException(nameof(SitePageSection), request.Id);

        entity.SectionKey = request.SectionKey;
        entity.Title = request.Title;
        entity.Subtitle = request.Subtitle;
        entity.HtmlContent = request.HtmlContent;
        entity.IconName = request.IconName;
        entity.ImagePath = request.ImagePath;
        entity.SortOrder = request.SortOrder;
        entity.IsActive = request.IsActive;
        entity.ExtraData = request.ExtraData;

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

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

        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
