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

namespace Application.Features.Admin.Popup.Search;

public sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var query = db.Popup.AsNoTracking();
        var total = await query.CountAsync(ct);
        var skip = (request.PageNum - 1) * request.PerPage;

        var list = await query
            .OrderByDescending(x => x.ID)
            .Skip(skip)
            .Take(request.PerPage)
            .Select(x => new
            {
                x.ID,
                x.PositionID,
                PositionCode = x.PopupPosition.Code,
                PositionSubject = x.PopupPosition.Subject,
                x.Subject,
                x.Link,
                x.StartAt,
                x.EndAt,
                x.Order,
                x.IsActive,
                x.UpdatedAt,
                x.CreatedAt
            })
            .ToListAsync(ct);

        var rows = list
            .Select((x, idx) => new Response.Row
            {
                Num = total - skip - idx,
                ID = x.ID,
                PositionID = x.PositionID,
                PositionCode = x.PositionCode,
                PositionSubject = x.PositionSubject,
                Subject = x.Subject,
                Link = x.Link,
                StartAt = x.StartAt?.ToString("yyyy-MM-dd HH:mm"),
                EndAt = x.EndAt?.ToString("yyyy-MM-dd HH:mm"),
                Order = x.Order,
                IsActive = x.IsActive,
                UpdatedAt = x.UpdatedAt.GetDateAt(),
                CreatedAt = x.CreatedAt.GetDateAt()
            })
            .ToList();

        return new Response
        {
            Total = total,
            List = rows
        };
    }
}