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

namespace Application.Features.Api.Faq.Item.GetByCode
{
    public sealed class Handler(IAppDbContext db, ICacheService cache) : IQueryHandler<Query, Response>
    {
        public async Task<Response> Handle(Query request, CancellationToken ct)
        {
            var cacheKey = CacheKeys.FaqItemByCode(request.Code ?? "all");
            var cached = await cache.GetAsync<Response>(cacheKey, ct);
            if (cached is not null)
            {
                return cached;
            }

            var query = db.FaqItem.AsNoTracking().Include(i => i.FaqCategory).AsQueryable();

            if (!string.IsNullOrWhiteSpace(request.Code))
            {
                query = query.Where(i => i.FaqCategory.Code == request.Code);
            }

            var total = await query.CountAsync(ct);

            var list = await query
                .OrderBy(i => i.Order)
                .ThenByDescending(i => i.ID)
                .Select(c => new
                {
                    c.ID,
                    c.CategoryID,
                    CategoryCode = c.FaqCategory.Code,
                    CategorySubject = c.FaqCategory.Subject,
                    c.Question,
                    c.Answer,
                    c.Order,
                    c.IsActive,
                    c.UpdatedAt,
                    c.CreatedAt
                })
                .ToListAsync(ct);

            var response = new Response
            {
                Total = total,
                List = [..list.Select(c => new Response.Item
                {
                    ID = c.ID,
                    CategoryID = c.CategoryID,
                    CategoryCode = c.CategoryCode,
                    CategorySubject = c.CategorySubject,
                    Question = c.Question,
                    Answer = c.Answer,
                    Order = c.Order,
                    IsActive = c.IsActive,
                    UpdatedAt = c.UpdatedAt,
                    CreatedAt = c.CreatedAt
                })]
            };

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