<?php

namespace App\Traits;


use Throwable;
use App\Jobs\IndexContent;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

trait ThrowsIndexation
{

    public static function bootThrowsIndexation()
    {

        static::saved(function ($item) {
            try {
                if (DB::transactionLevel() > 0) {

                    DB::afterCommit(function () use ($item) {
                        IndexContent::dispatch($item, IndexContent::ACTION_REINDEX_RELATIONS);
                    });
                } else {
                    IndexContent::dispatch($item, IndexContent::ACTION_REINDEX_RELATIONS);
                }
            } catch (Throwable $t) {
                Log::error($t);
            }
        });
    }
}
