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

namespace Application.Features.Api.News.GetArticles;

public sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var query = db.RssNewsArticle.AsNoTracking().Include(x => x.RssFeedSource).AsQueryable();

        if (request.RssFeedSourceID.HasValue)
        {
            query = query.Where(x => x.RssFeedSourceID == request.RssFeedSourceID.Value);
        }

        if (!string.IsNullOrWhiteSpace(request.Keyword))
        {
            var kw = request.Keyword.Trim();
            query = query.Where(x => x.Title.Contains(kw) || (x.Description != null && x.Description.Contains(kw)));
        }

        query = query.OrderByDescending(x => x.PublishedAt ?? x.CreatedAt);

        var total = await query.CountAsync(ct);

        var list = await query
            .Skip((request.Page - 1) * request.PerPage)
            .Take(request.PerPage)
            .Select(x => new Response.Row(
                x.ID,
                x.RssFeedSourceID,
                x.RssFeedSource.Name,
                x.Title,
                x.Link,
                x.Author,
                x.Description,
                x.ImageUrl,
                x.SourceName,
                x.Categories,
                x.CommentCount,
                x.PublishedAt,
                x.CreatedAt
            ))
            .ToListAsync(ct);

        return new Response(total, list);
    }
}