namespace Brizco.Repository.Handlers.Section;

public class DeleteSectionCommandHandler : IRequestHandler<DeleteSectionCommand, bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public DeleteSectionCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(DeleteSectionCommand request, CancellationToken cancellationToken)
    {
        var section = await _repositoryWrapper.SetRepository<Domain.Entities.Complex.Section>()
            .TableNoTracking
            .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
        if (section == null)
            throw new AppException("Section not found", ApiResultStatusCode.NotFound);

        var positions = await _repositoryWrapper.SetRepository<Domain.Entities.Complex.Position>()
            .TableNoTracking
            .Where(p => p.SectionId == section.Id)
            .CountAsync(cancellationToken);
        if (positions > 0)
            throw new AppException("این سکشن پوزیشن فعال دارد ، نخست پوزیشن های سکشن را حذف کرده یا منتقل کنید");

        _repositoryWrapper.SetRepository<Domain.Entities.Complex.Section>()
            .Delete(section);

        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;
    }
}