<?php

namespace LaraBB\Post\Actions;

use LaraBB\Forum\Tasks\Forum\UpdateTask as UpdateForumTask;
use Exception;
use LaraBB\Post\Models\Post;
use LaraBB\Post\Tasks\DestroyTask as DestroyPostTask;
use LaraBB\Post\UI\Web\Requests\Destroy;
use LaraBB\Thread\Models\Thread;
use LaraBB\Thread\Tasks\DestroyTask as DestroyThreadTask;
use LaraBB\Thread\Tasks\UpdateTask as UpdateThreadTask;

/**
 * Class DestroyAction
 * @package LaraBB\Post\Actions
 */
class DestroyAction
{
    /**
     * DestroyAction constructor.
     * @param DestroyPostTask $destroyPostTask
     * @param UpdateThreadTask $updateThreadTask
     * @param UpdateForumTask $updateForumTask
     * @param DestroyThreadTask $destroyThreadTask
     */
    public function __construct(
        private readonly DestroyPostTask $destroyPostTask,
        private readonly UpdateThreadTask $updateThreadTask,
        private readonly UpdateForumTask $updateForumTask,
        private readonly DestroyThreadTask $destroyThreadTask
    ) {

    }

    /**
     * @param Destroy $request
     * @return false
     * @throws Exception
     */
    public function run(Destroy $request): bool
    {
        $thread = $request->thread;

        if(!$this->destroyPostTask->run($request->post)) {
            return false;
        }

        $thread->posts--;

        /** @var Post $lastPost */
        $lastPost = $thread->postings()->latest()->first();
        $this->updateThreadTask->run($thread, [
            'posts'         => $thread->posts,
            'lastpost_uuid' => $lastPost->uuid ?? $thread->firstpost_uuid
        ]);

        $this->updateForumTask->run($thread->forum, [
            'lastpost_uuid' => $lastPost->uuid ?? $thread->firstpost_uuid,
            'posting_count' => $thread->forum->posting_count - 1
        ]);

        if($thread->posts == 0) {

            /** @var Thread $latestThread */
            $latestThread = $thread->forum->threads()->latest()->first();

            $this->updateForumTask->run($thread->forum, [
                'lastpost_uuid' => $latestThread->lastpost_uuid,
                'thread_count'  => $thread->forum->thread_count - 1
            ]);

            $this->destroyThreadTask->run($thread);
        }

        return true;
    }
}
