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

namespace CMSMicroservice.Application.SitePageCQ.Commands.DeleteSitePage;

public class DeleteSitePageCommandHandler : IRequestHandler<DeleteSitePageCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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

        entity.IsDeleted = true;

        // حذف نرم بخش‌های وابسته
        foreach (var section in entity.Sections.Where(s => !s.IsDeleted))
        {
            section.IsDeleted = true;
        }

        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
