using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.SitePageSettingsCQ.Queries.GetAllPageSettings;

// ── Query ──
public class GetAllPageSettingsQuery : IRequest<List<PageSettingsSummaryDto>>
{
}

// ── Handler ──
public class GetAllPageSettingsQueryHandler : IRequestHandler<GetAllPageSettingsQuery, List<PageSettingsSummaryDto>>
{
    private readonly IApplicationDbContext _context;

    public GetAllPageSettingsQueryHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<List<PageSettingsSummaryDto>> Handle(GetAllPageSettingsQuery request, CancellationToken cancellationToken)
    {
        return await _context.SitePageSettingsEntities
            .Where(x => !x.IsDeleted)
            .OrderBy(x => x.Id)
            .Select(x => new PageSettingsSummaryDto
            {
                Id = x.Id,
                PageKey = x.PageKey,
                Title = x.Title,
                IsActive = x.IsActive,
                ImageCount = x.Images.Count(i => !i.IsDeleted),
                LastModified = x.LastModified ?? x.Created
            })
            .ToListAsync(cancellationToken);
    }
}

// ── DTO ──
public class PageSettingsSummaryDto
{
    public long Id { get; set; }
    public string PageKey { get; set; } = string.Empty;
    public string Title { get; set; } = string.Empty;
    public bool IsActive { get; set; }
    public int ImageCount { get; set; }
    public DateTime LastModified { get; set; }
}
