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

namespace Application.Features.Admin.Banner.Item.Search;

public sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var query = db.BannerItem.AsNoTracking().Include(c => c.BannerPosition).AsQueryable();

        if (request.PositionID.HasValue)
        {
            query = query.Where(c => c.PositionID == request.PositionID.Value);
        }

        if (!string.IsNullOrWhiteSpace(request.Keyword))
        {
            var kw = request.Keyword.Trim();
            query = query.Where(c => c.Subject.Contains(kw));
        }

        var total = await query.CountAsync(ct);

        var list = await query
            .OrderByDescending(c => c.ID)
            .Skip((request.PageNum - 1) * request.PerPage)
            .Take(request.PerPage)
            .Select(c=> new
            {
                c.ID,
                c.PositionID,
                PositionCode = c.BannerPosition.Code,
                PositionSubject = c.BannerPosition.Subject,
                c.Subject,
                c.DesktopImage,
                c.MobileImage,
                c.Link,
                c.Order,
                c.IsActive,
                c.StartAt,
                c.EndAt,
                c.UpdatedAt,
                c.CreatedAt
            })
            .ToListAsync(ct);

        var startNum = total - ((request.PageNum - 1) * request.PerPage);

        return new Response(
            total,
            [..list.Select((c, i) => new Response.Row(
                Num: startNum - i,
                c.ID,
                c.PositionID,
                c.PositionCode,
                c.PositionSubject,
                c.Subject,
                c.DesktopImage,
                c.MobileImage,
                c.Link,
                c.Order,
                c.IsActive,
                c.StartAt,
                c.EndAt,
                c.UpdatedAt,
                c.CreatedAt
            ))]
        );
    }
}