using Application.Abstractions.Messaging;
﻿using Application.Abstractions.Data;
using SharedKernel;
using SharedKernel.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;

namespace Application.Features.Admin.Document.Search
{
    public sealed class Handler(IAppDbContext db, IOptions<AppSettings> settings) : IQueryHandler<Query, Response>
    {
        public async Task<Response> Handle(Query request, CancellationToken ct)
        {
            var total = await db.Document.CountAsync(ct);
            var list = await db.Document.AsNoTracking().OrderByDescending(c => c.ID).Skip((request.Page - 1) * request.PerPage).Take(request.PerPage).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,
                    Link = $"{settings.Value.App.FrontURL}/docs/{c.Code}",
                    Code = c.Code,
                    Subject = c.Subject,
                    Content = c.Content,
                    Views = c.Views.ToString("N0"),
                    IsActive = c.IsActive ? 'Y' : 'N',
                    UpdatedAt = c.UpdatedAt.GetDateAt() ?? "-",
                    CreatedAt = c.CreatedAt.GetDateAt()
                })]
            };
        }
    }
}