using LiteCqrs;
using Microsoft.EntityFrameworkCore;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;

namespace TeleWave.Application.Images.GetImageFile;

public sealed class GetImageFileQueryHandler(IAppDbContext dbContext, IImageStore storage)
    : IQueryHandler<GetImageFileQuery, Result<string>>
{
    public async Task<Result<string>> Handle(
        GetImageFileQuery query,
        CancellationToken cancellationToken
    )
    {
        var image = await dbContext
            .Images.AsNoTracking()
            .FirstOrDefaultAsync(i => i.Id == query.Id, cancellationToken);
        if (image is null)
            return Result.Failure<string>(ImageErrors.NotFound);

        var path = storage.ResolvePath(image.Id, image.FileExtension);
        return path is null ? Result.Failure<string>(ImageErrors.NotFound) : Result.Success(path);
    }
}
