using Femto.Modules.Media.Contracts.LoadFile.Dto;
using Femto.Modules.Media.Data;
using Femto.Modules.Media.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Femto.Modules.Media.Contracts.LoadFile;

internal class LoadFileQueryHandler(IStorageProvider storage, MediaContext context)
    : IRequestHandler<LoadFileQuery, LoadFileQueryResult>
{
    public async Task<LoadFileQueryResult> Handle(
        LoadFileQuery query,
        CancellationToken cancellationToken
    )
    {
        var blob = await context
            .SavedBlobs.Where(b => b.Id == query.FileId)
            .SingleAsync(cancellationToken: cancellationToken);

        var data = await storage.LoadBlob(query.FileId.ToString());

        return new(data, blob.Type, blob.Size);
    }
}
