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

namespace Application.Features.Admin.Faq.Category.GetAll
{
    public sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
    {
        public async Task<Response> Handle(Query request, CancellationToken ct)
        {
            var items = await db.FaqCategory
                .AsNoTracking()
                .Include(c => c.FaqItems)
                .OrderBy(c => c.Order)
                .ThenByDescending(c => c.ID)
                .Select(c => new
                {
                    c.ID,
                    c.Code,
                    c.Subject,
                    c.Order,
                    c.IsActive,
                    FaqItemCount = c.FaqItems.Count,
                    c.UpdatedAt,
                    c.CreatedAt
                })
                .ToListAsync(ct);

            return new Response(
                items.Count,
                [..items.Select((c, i) => new Response.Row(
                    i + 1,
                    c.ID,
                    i,
                    c.Code,
                    c.Subject,
                    c.Order,
                    c.IsActive,
                    (ushort)c.FaqItemCount,
                    c.UpdatedAt,
                    c.CreatedAt
            ))]);
        }
    }
}