<?php

namespace LaraBB\Settings\Actions\Prefix;

use App\Traits\PivotData;
use Illuminate\Database\Connection;
use LaraBB\Settings\Tasks\Prefix\FindTask as FindPrefixTask;
use LaraBB\Settings\Tasks\Prefix\UpdateTask as UpdatePrefixTask;
use LaraBB\Settings\UI\Web\Requests\Prefix\Update;
use Throwable;

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

    /**
     * UpdateAction constructor.
     * @param FindPrefixTask $getPrefixTask
     * @param UpdatePrefixTask $updatePrefixTask
     * @param Connection $connection
     */
    public function __construct(
        private readonly FindPrefixTask $getPrefixTask,
        private readonly UpdatePrefixTask $updatePrefixTask,
        private readonly Connection $connection
    ) {

    }

    /**
     * @param Update $request
     * @return bool
     */
    public function run(Update $request): bool
    {
        $prefix = $this->getPrefixTask->byUuid($request->post('uuid'));

        try {
            $this->connection->transaction(function() use($prefix, $request) {
                $this->updatePrefixTask->run($prefix, $this->preparePrefixData($request));
            });
        } catch (Throwable $t) {
            return false;
        }

        return true;
    }

    /**
     * @param Update $request
     * @return array
     */
    private function preparePrefixData(Update $request): array
    {
        return [
            'updated_uuid'  => $request->user()->uuid,
            'prefix'        => $request->post('prefix'),
            'display_style' => $request->post('display_style'),
            'forums'        => $this->preparePivotData($request, 'forums'),
        ];
    }
}
