using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Content;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.SitePageCQ.Queries.GetSitePageByKey;

public class GetSitePageByKeyQuery : IRequest<GetSitePage.SitePageDto>
{
    public string PageKey { get; set; } = default!;
}

public class GetSitePageByKeyQueryHandler : IRequestHandler<GetSitePageByKeyQuery, GetSitePage.SitePageDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetSitePage.SitePageDto> Handle(GetSitePageByKeyQuery request, CancellationToken cancellationToken)
    {
        var entity = await _context.SitePages
            .Include(x => x.Sections.Where(s => !s.IsDeleted).OrderBy(s => s.SortOrder))
            .FirstOrDefaultAsync(x => x.PageKey == request.PageKey && !x.IsDeleted, cancellationToken);

        if (entity == null)
            throw new NotFoundException(nameof(SitePage), request.PageKey);

        return GetSitePage.GetSitePageQueryHandler.MapToDto(entity);
    }
}
