<?php

namespace LaraBB\Thread\Tasks;

use Exception;
use LaraBB\Post\Models\Post;
use LaraBB\Thread\Models\Thread;

/**
 * Class DestroyThreadTask
 * @package LaraBB\Thread\Tasks
 */
class DestroyTask
{
    /**
     * @param Thread $thread
     * @return bool|null
     * @throws Exception
     */
    public function run(Thread $thread): ?bool
    {
        $thread->users()->detach();
        $thread->groups()->detach();

        $thread->load('postings');

        /** @var Post $posting */
        foreach($thread->postings as $posting) {
            $posting->users()->detach();
            $posting->groups()->detach();
        }

        $thread->postings()->delete();

        return $thread->delete();
    }
}
