<?php

namespace LaraBB\Post\Actions;

use App\Traits\PivotData;
use LaraBB\Post\Tasks\UpdateTask as UpdatePostTask;
use LaraBB\Post\UI\Web\Requests\Update;
use LaraBB\Thread\Tasks\UpdateTask as UpdateThreadTask;
use Str;

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

    /**
     * UpdateAction constructor.
     * @param UpdatePostTask $updatePostTask
     * @param UpdateThreadTask $updateThreadTask
     */
    public function __construct(
        private readonly UpdatePostTask $updatePostTask,
        private readonly UpdateThreadTask $updateThreadTask
    ) {

    }

    /**
     * @param Update $request
     * @return bool
     */
    public function run(Update $request): bool
    {
        if($request->post->uuid === $request->post->thread->firstpost_uuid) {
            $this->updateThreadTask->run($request->post->thread, $this->prepareThreadData($request));

            $request->post->thread->load('postings');
            $postings = $request->post->thread->postings->except($request->post->uuid);

            if(!empty($postings)) {
                foreach($postings as $post) {
                    $this->updatePostTask->run($post, ['title' => 'RE: ' . $request->post('title')]);
                }
            }
        }

        return $this->updatePostTask->run($request->post, $this->preparePostData($request));
    }

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

    /**
     * @param Update $request
     * @return array
     */
    private function prepareThreadData(Update $request): array
    {
        return [
            'prefix_uuid' => $request->post('prefix'),
            'title'       => $request->post('title'),
            'slug'        => Str::slug($request->post('title')) . '-' . $request->post->thread->id,
            'users'       => $this->preparePivotData($request, 'users'),
            'groups'      => $this->preparePivotData($request, 'groups'),
        ];
    }
}
