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

namespace CMSMicroservice.Application.SitePageCQ.Queries.GetAllSitePages;

public class GetAllSitePagesQuery : IRequest<List<SitePageListItemDto>>
{
}

public class SitePageListItemDto
{
    public long Id { get; set; }
    public string PageKey { get; set; } = default!;
    public string Title { get; set; } = default!;
    public bool IsActive { get; set; }
    public int SectionCount { get; set; }
    public DateTime Created { get; set; }
    public DateTime? LastModified { get; set; }
}

public class GetAllSitePagesQueryHandler : IRequestHandler<GetAllSitePagesQuery, List<SitePageListItemDto>>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<List<SitePageListItemDto>> Handle(GetAllSitePagesQuery request, CancellationToken cancellationToken)
    {
        var pages = await _context.SitePages
            .Include(x => x.Sections)
            .Where(x => !x.IsDeleted)
            .OrderBy(x => x.PageKey)
            .Select(x => new SitePageListItemDto
            {
                Id = x.Id,
                PageKey = x.PageKey,
                Title = x.Title,
                IsActive = x.IsActive,
                SectionCount = x.Sections.Count(s => !s.IsDeleted),
                Created = x.Created,
                LastModified = x.LastModified
            })
            .ToListAsync(cancellationToken);

        return pages;
    }
}
