using Application.Abstractions.Messaging;
using Application.Abstractions.Data;
using Application.Abstractions.Cache;
using SharedKernel.Storage;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Admin.Faq.Item.Update
{
    public sealed class Handler(IAppDbContext db, IEditorImageService editorImage, ICacheService cache) : ICommandHandler<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);
            await cache.RemoveByPrefixAsync("faq:item:", ct);
        }
    }
}