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

namespace Application.Features.Admin.Forum.Post.DeleteThumbnail;

public sealed class Handler(IAppDbContext db, IFileStorage fileStorage) : ICommandHandler<Command>
{
    public async Task Handle(Command request, CancellationToken ct)
    {
        var post = await db.Post.FirstOrDefaultAsync(x => x.ID == request.ID, ct);
        if (post is null)
        {
            throw new KeyNotFoundException("게시글을 찾을 수 없습니다.");
        }

        if (!string.IsNullOrEmpty(post.Thumbnail))
        {
            fileStorage.DeleteByUrl(post.Thumbnail);
            post.Thumbnail = null;
            await db.SaveChangesAsync(ct);
        }
    }
}