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

namespace Application.Features.Admin.Faq.Item.Search
{
    public sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
    {
        public async Task<Response> Handle(Query request, CancellationToken ct)
        {
            var query = db.FaqItem.AsNoTracking().Include(i => i.FaqCategory).AsQueryable();

            if (request.CategoryID.HasValue)
            {
                query = query.Where(i => i.CategoryID == request.CategoryID.Value);
            }

            if (!string.IsNullOrWhiteSpace(request.Keyword))
            {
                var keyword = request.Keyword!.Trim();
                query = query.Where(i =>
                    EF.Functions.Like(i.Question, $"%{keyword}%") ||
                    EF.Functions.Like(i.Answer, $"%{keyword}%")
                );
            }

            var total = await query.CountAsync(ct);

            var list = await query
                .OrderBy(i => i.Order)
                .ThenByDescending(i => i.ID)
                .Skip((request.Page - 1) * request.PerPage)
                .Take(request.PerPage)
                .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);

            return new Response
            {
                Total = total,
                List = [..list.Select((c, i) => new Response.Item
                {
                    Num = total - ((request.Page - 1) * request.PerPage) - i,
                    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
                })]
            };
        }
    }
}