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

namespace Application.Features.Api.Faq.Category.GetActive;

public sealed class Handler(IAppDbContext db, ICacheService cache) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var cached = await cache.GetAsync<Response>(CacheKeys.FaqCategoryActive, ct);
        if (cached is not null)
        {
            return cached;
        }

        var rows = await db.FaqCategory
            .AsNoTracking()
            .Where(c => c.IsActive)
            .OrderBy(c => c.Order)
            .ThenByDescending(c => c.ID)
            .Select(c => new Response.Row(
                c.ID,
                c.Code,
                c.Subject,
                c.Order
            ))
            .ToListAsync(ct);

        var response = new Response(rows.Count, rows);

        await cache.SetAsync(CacheKeys.FaqCategoryActive, response, ct);
        return response;
    }
}
