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

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

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

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

        entity.Title = request.Title;
        entity.MetaDescription = request.MetaDescription;
        entity.HeroTitle = request.HeroTitle;
        entity.HeroSubtitle = request.HeroSubtitle;
        entity.HeroImagePath = request.HeroImagePath;
        entity.IsActive = request.IsActive;

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

            entity.HeroImagePath = result.Main.Path;
        }

        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
