using SharedKernel.Storage;
using Application.Abstractions.Data;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Faq.Item.Update
{
    public sealed class Handler(IAppDbContext db, IEditorImageService editorImage) : IRequestHandler<Command>
    {
        public async Task Handle(Command request, CancellationToken ct)
        {
            var item = await db.FaqItem.FirstOrDefaultAsync(c => c.ID == request.ID, ct);
            if (item is null)
            {
                throw new Exception("해당 FAQ를 찾을 수 없습니다.");
            }

            var path = new FileStoragePath(UploadTarget.Editor, UploadFolder.Faq, request.ID);

            item.Update(
                request.CategoryID,
                request.Question,
                await editorImage.UploadAsync(request.Answer, path, ct),
                request.Order,
                request.IsActive
            );

            await db.SaveChangesAsync(ct);
        }
    }
}