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

namespace CMSMicroservice.Application.SitePageSettingsCQ.Commands.SavePageSettings;

// ── Command ──
public class SavePageSettingsCommand : IRequest<SavePageSettingsResult>
{
    public string PageKey { get; set; } = default!;
    public string Title { get; set; } = default!;
    public string? MetaDescription { get; set; }
    public string? HeroTitle { get; set; }
    public string? HeroSubtitle { get; set; }
    public bool IsActive { get; set; }
    public string? SettingsJson { get; set; }

    // Hero image upload
    public byte[]? ImageFileBytes { get; set; }
    public string? ImageFileMime { get; set; }
    public string? ImageFileName { get; set; }
}

public class SavePageSettingsResult
{
    public long Id { get; set; }
    public bool Success { get; set; }
}

// ── Handler ──
public class SavePageSettingsCommandHandler : IRequestHandler<SavePageSettingsCommand, SavePageSettingsResult>
{
    private readonly IApplicationDbContext _context;
    private readonly IFileManager _fileManager;

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

    public async Task<SavePageSettingsResult> Handle(SavePageSettingsCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.SitePageSettingsEntities
            .FirstOrDefaultAsync(x => x.PageKey == request.PageKey && !x.IsDeleted, cancellationToken);

        if (entity == null)
        {
            // ایجاد صفحه جدید (فقط برای seed اولیه — صفحات ثابت هستند)
            entity = new SitePageSettings
            {
                PageKey = request.PageKey,
            };
            _context.SitePageSettingsEntities.Add(entity);
        }

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

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

            entity.HeroImagePath = result.Main.Path;
        }

        await _context.SaveChangesAsync(cancellationToken);

        return new SavePageSettingsResult { Id = entity.Id, Success = true };
    }
}
