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

namespace Application.Features.Admin.Popup.Update;

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

        var popup = await db.Popup.FirstOrDefaultAsync(x => x.ID == request.ID, ct);
        if (popup is null)
        {
            throw new Exception("팝업을 찾을 수 없습니다.");
        }

        popup.Update(
            request.PositionID,
            request.Subject,
            request.Content,
            request.Link,
            request.StartAt,
            request.EndAt,
            request.Order,
            request.IsActive
        );

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