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

namespace Application.Features.Api.Popup.GetAll;

public sealed class Handler(IAppDbContext db, ICacheService cache) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var cacheKey = CacheKeys.PopupByCode(request.Code);
        var cached = await cache.GetAsync<Response>(cacheKey, ct);
        if (cached is not null)
        {
            return cached;
        }

        var query = db.Popup.AsNoTracking().Where(x => x.PopupPosition.Code == request.Code);

        var total = await query.CountAsync(ct);

        var list = await query
            .OrderBy(x => x.Order)
            .ThenByDescending(x => x.ID)
            .Select(x => new
            {
                x.ID,
                x.PositionID,
                x.Subject,
                x.Content,
                x.Link,
                x.StartAt,
                x.EndAt,
                x.Order,
                x.IsActive,
                x.UpdatedAt,
                x.CreatedAt
            })
            .ToListAsync(ct);

        var response = new Response
        {
            Total = total,
            List = [..list.Select(x => new Response.Row
            {
                ID = x.ID,
                PositionID = x.PositionID,
                Subject = x.Subject,
                Content = x.Content,
                Link = x.Link,
                StartAt = x.StartAt,
                EndAt = x.EndAt,
                Order = x.Order,
                IsActive = x.IsActive,
                UpdatedAt = x.UpdatedAt,
                CreatedAt = x.CreatedAt
            })]
        };

        await cache.SetAsync(cacheKey, response, ct);
        return response;
    }
}