<?php

namespace LaraBB\Settings\Actions\Prefix;

use App\Traits\PivotData;
use Illuminate\Database\Connection;
use LaraBB\Settings\Tasks\Prefix\StoreTask as StorePrefixTask;
use LaraBB\Settings\UI\Web\Requests\Prefix\Store;
use Throwable;

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

    /**
     * StoreAction constructor.
     * @param StorePrefixTask $storePrefixTask
     * @param Connection $connection
     */
    public function __construct(
        private readonly StorePrefixTask $storePrefixTask,
        private readonly Connection $connection
    ) {
    }


    /**
     * @param Store $request
     * @return bool
     */
    public function run(Store $request): bool
    {
        try {
            $this->connection->transaction(function () use($request) {
                $this->storePrefixTask->run($this->preparePrefixData($request));
            });
        } catch (Throwable $t) {
            return false;
        }

        return true;
    }

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