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

namespace Application.Features.Admin.Popup.Position.GetAll;

public sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var rows = await db.PopupPosition
            .AsNoTracking()
            .OrderByDescending(c => c.ID)
            .Select(c => new
            {
                c.ID,
                c.Code,
                c.Subject,
                PopupRows = c.Popups.Count,
                c.IsActive,
                c.UpdatedAt,
                c.CreatedAt
            })
            .ToListAsync(ct);

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