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

namespace TeleWave.Application.Images.ListImages;

public sealed class ListImagesQueryHandler(IAppDbContext dbContext)
    : IQueryHandler<ListImagesQuery, Result<IReadOnlyList<ImageDto>>>
{
    public async Task<Result<IReadOnlyList<ImageDto>>> Handle(
        ListImagesQuery query,
        CancellationToken cancellationToken
    )
    {
        var images = await dbContext
            .Images.AsNoTracking()
            .Where(i => i.Category == query.Category)
            .OrderByDescending(i => i.CreatedAt)
            .Select(i => new ImageDto(i.Id, i.Category, i.OriginalFileName, i.CreatedAt))
            .ToListAsync(cancellationToken);

        return Result.Success<IReadOnlyList<ImageDto>>(images);
    }
}
