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

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

public sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var rows = await db.BannerPosition
            .AsNoTracking()
            .OrderByDescending(c => c.ID)
            .Select(c => new
            {
                c.ID,
                c.Code,
                c.Subject,
                BannerItemRows = c.BannerItems.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.BannerItemRows,
                c.IsActive,
                c.UpdatedAt,
                c.CreatedAt
            ))]
        );
    }
}