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

namespace Application.Features.Api.News.GetArticle;

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

        if (item is null)
        {
            return Result.Failure<Response>(Error.NotFound("News.NotFound", "뉴스 기사를 찾을 수 없습니다."));
        }

        return new Response(
            item.ID,
            item.RssFeedSourceID,
            item.RssFeedSource.Name,
            item.Title,
            item.Link,
            item.Guid,
            item.Author,
            item.Description,
            item.Content,
            item.ImageUrl,
            item.SourceName,
            item.Categories,
            item.CommentCount,
            item.PublishedAt,
            item.CreatedAt
        );
    }
}