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

namespace CMSMicroservice.Application.SitePageCQ.Commands.CreateSitePageSection;

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

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

    public async Task<long> Handle(CreateSitePageSectionCommand request, CancellationToken cancellationToken)
    {
        var page = await _context.SitePages.FirstOrDefaultAsync(x => x.Id == request.SitePageId && !x.IsDeleted, cancellationToken);
        if (page == null)
            throw new NotFoundException(nameof(SitePage), request.SitePageId);

        var maxSortOrder = await _context.SitePageSections
            .Where(x => x.SitePageId == request.SitePageId && !x.IsDeleted)
            .MaxAsync(x => (int?)x.SortOrder, cancellationToken) ?? 0;

        var sectionKey = string.IsNullOrWhiteSpace(request.SectionKey)
            ? $"section-{Guid.NewGuid():N}"[..20]
            : request.SectionKey.Trim().ToLower();

        var entity = new SitePageSection
        {
            SitePageId = request.SitePageId,
            SectionKey = sectionKey,
            Title = request.Title,
            Subtitle = request.Subtitle,
            HtmlContent = request.HtmlContent,
            IconName = request.IconName,
            ImagePath = request.ImagePath,
            SortOrder = maxSortOrder + 1,
            IsActive = request.IsActive,
            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;
        }

        _context.SitePageSections.Add(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return entity.Id;
    }
}
