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

namespace Application.Features.Popup.Create;

public sealed class Handler(IAppDbContext db, IEditorImageService editorImage) : IRequestHandler<Command, int>
{
    public async Task<int> Handle(Command request, CancellationToken ct)
    {
        if (request.StartAt > request.EndAt)
        {
            throw new Exception("팝업의 종료일은 시작일보다 이전일 수 없습니다.");
        }

        var popup = Domain.Entities.Page.Popup.Create(
            request.Subject,
            null,
            request.Link,
            request.StartAt,
            request.EndAt,
            request.Order,
            request.IsActive
        );

        await db.Popup.AddAsync(popup);
        await db.SaveChangesAsync(ct);

        var path = new FileStoragePath(UploadTarget.Editor, UploadFolder.Popup, popup.ID);
        var html = await editorImage.UploadAsync(request.Content, path, ct);

        popup.SetContent(html);
        await db.SaveChangesAsync(ct);

        return popup.ID;
    }
}