<?php

namespace LaraBB\Post\Actions;

use LaraBB\Forum\Tasks\Forum\UpdateTask as UpdateForumTask;
use App\Traits\PivotData;
use LaraBB\Post\Tasks\FindTask as FindPostTask;
use LaraBB\Post\Tasks\StoreTask as StorePostTask;
use LaraBB\Post\UI\Web\Requests\Store;
use LaraBB\Thread\Tasks\UpdateTask as UpdateThreadTask;

/**
 * Class StoreAction
 * @package LaraBB\Post\Actions
 */
class StoreAction
{
    use PivotData;

    /**
     * StoreAction constructor.
     * @param StorePostTask $storePostTask
     * @param UpdateThreadTask $updateThreadTask
     * @param FindPostTask $getPostTask
     * @param UpdateForumTask $updateForumTask
     */
    public function __construct(
        private readonly StorePostTask $storePostTask,
        private readonly UpdateThreadTask $updateThreadTask,
        private readonly FindPostTask $getPostTask,
        private readonly UpdateForumTask $updateForumTask
    ) {

    }

    /**
     * @param Store $request
     * @return false|int
     */
    public function run(Store $request)
    {
        $post = $this->storePostTask->run($this->preparePostData($request));

        if (!$post) {
            return false;
        }

        $post = $this->getPostTask->byUuid($post->uuid);
        $this->updateThreadTask->run($request->thread, [
            'posts'         => $request->thread->posts + 1,
            'lastpost_uuid' => $post->uuid
        ]);

        $this->updateForumTask->run($request->thread->forum, [
            'posting_count' => $request->thread->forum->posting_count + 1,
            'lastpost_uuid' => $post->uuid
        ]);

        return $post->id;
    }

    /**
     * @param Store $request
     * @return array
     */
    private function preparePostData(Store $request): array
    {
        return [
            'created_uuid' => $request->user()->uuid,
            'updated_uuid' => $request->user()->uuid,
            'thread_uuid'  => $request->post('thread_uuid'),
            'title'        => $request->post('title'),
            'content'      => $request->post('content'),
            'users'        => $this->preparePivotData($request, 'users'),
            'groups'       => $this->preparePivotData($request, 'groups')
        ];
    }
}
