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

// ── Command ──
public class SavePageImageCommand : IRequest<SavePageImageResult>
{
    public long Id { get; set; }  // 0 = ایجاد جدید
    public long SitePageSettingsId { get; set; }
    public string ImageGroup { get; set; } = default!;
    public string? Title { get; set; }
    public string? Subtitle { get; set; }
    public string? Description { get; set; }
    public string? LinkUrl { get; set; }
    public string? IconName { get; set; }
    public int SortOrder { get; set; }
    public bool IsActive { get; set; } = true;

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

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

// ── Handler ──
public class SavePageImageCommandHandler : IRequestHandler<SavePageImageCommand, SavePageImageResult>
{
    private readonly IApplicationDbContext _context;
    private readonly IFileManager _fileManager;

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

    public async Task<SavePageImageResult> Handle(SavePageImageCommand request, CancellationToken cancellationToken)
    {
        SitePageImage entity;

        if (request.Id > 0)
        {
            // ویرایش
            entity = await _context.SitePageImages
                .FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken)
                ?? throw new Exception($"تصویر با شناسه {request.Id} یافت نشد");
        }
        else
        {
            // ایجاد جدید
            entity = new SitePageImage
            {
                SitePageSettingsId = request.SitePageSettingsId,
                ImageGroup = request.ImageGroup,
                ImagePath = string.Empty // placeholder — will be set below
            };
            _context.SitePageImages.Add(entity);
        }

        entity.Title = request.Title;
        entity.Subtitle = request.Subtitle;
        entity.Description = request.Description;
        entity.LinkUrl = request.LinkUrl;
        entity.IconName = request.IconName;
        entity.SortOrder = request.SortOrder;
        entity.IsActive = request.IsActive;

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

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

        await _context.SaveChangesAsync(cancellationToken);

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