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

namespace Application.Features.Admin.Popup.Create;

public sealed class Handler(IAppDbContext db, IEditorImageService editorImage, ICacheService cache) : ICommandHandler<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.Popup.Create(
            request.PositionID,
            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);
        await cache.RemoveByPrefixAsync("popup:", ct);

        return popup.ID;
    }
}