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

namespace CMSMicroservice.Application.SitePageCQ.Commands.DeleteSitePageSection;

public class DeleteSitePageSectionCommandHandler : IRequestHandler<DeleteSitePageSectionCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<Unit> Handle(DeleteSitePageSectionCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.SitePageSections.FindAsync(new object[] { request.Id }, cancellationToken);
        if (entity == null || entity.IsDeleted)
            throw new NotFoundException(nameof(SitePageSection), request.Id);

        entity.IsDeleted = true;

        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
