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

namespace Application.Features.Faq.Item.Create
{
    public sealed class Handler(IAppDbContext db, IEditorImageService editorImage) : IRequestHandler<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();
        }
    }
}