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

namespace Application.Features.Admin.Crypto.News.Source.Search
{
    public sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
    {
        public async Task<Response> Handle(Query request, CancellationToken ct)
        {
            var query = db.RssFeedSource.AsNoTracking().AsQueryable();

            var total = await query.CountAsync(ct);

            var list = await query
                .OrderByDescending(c => c.ID)
                .Skip((request.PageNum - 1) * request.PerPage)
                .Take(request.PerPage)
                .Select(c => new
                {
                    c.ID,
                    c.Name,
                    c.Url,
                    c.Description,
                    c.IntervalMinutes,
                    c.IsActive,
                    c.LastFetchedAt,
                    c.CreatedAt
                })
                .ToListAsync(ct);

            var startNum = total - ((request.PageNum - 1) * request.PerPage);

            return new Response(
                total,
                [..list.Select((c, i) => new Response.Row(
                    Num: startNum - i,
                    c.ID,
                    c.Name,
                    c.Url,
                    c.Description,
                    c.IntervalMinutes,
                    c.IsActive,
                    c.LastFetchedAt,
                    c.CreatedAt
                ))]
            );
        }
    }
}