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

namespace Application.Features.Admin.Faq.Item.Create
{
    public sealed class Handler(IAppDbContext db, IEditorImageService editorImage, ICacheService cache) : ICommandHandler<Command>
    {
        public async Task Handle(Command request, CancellationToken ct)
        {
            if (await db.FaqItem.AnyAsync(c => c.Question == request.Question))
            {
                throw new Exception("�̹� ��ϵ� FAQ�Դϴ�.");
            }

            var faq = Domain.Entities.Page.Faq.FaqItem.Create(
                request.CategoryID,
                request.Question,
                null,
                request.Order,
                request.IsActive
            );

            await db.FaqItem.AddAsync(faq, ct);

            int affectedRows = await db.SaveChangesAsync();
            if (affectedRows <= 0)
            {
                throw new Exception("FAQ ��� �� ������ �߻��߽��ϴ�.");
            }

            var path = new FileStoragePath(UploadTarget.Editor, UploadFolder.Faq, faq.ID);
            var html = await editorImage.UploadAsync(request.Answer, path, ct);

            faq.SetContent(html);

            await db.SaveChangesAsync();
            await cache.RemoveByPrefixAsync("faq:item:", ct);
        }
    }
}