<?php

namespace LaraBB\Category\Actions\Admin;

use Illuminate\Database\Connection;
use JetBrains\PhpStorm\ArrayShape;
use LaraBB\Category\Tasks\StoreTask;
use LaraBB\Category\UI\Web\Requests\Store;
use Throwable;

/**
 * Class StoreAction
 * @package LaraBB\Category\Actions\Admin
 */
class StoreAction
{
    /**
     * StoreAction constructor.
     * @param StoreTask $storeCategoryTask
     * @param Connection $connection
     */
    public function __construct(
        private readonly StoreTask $storeCategoryTask,
        private readonly Connection $connection
    ) {
    }

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

        return true;
    }

    #[ArrayShape([
        'created_uuid' => "mixed",
        'updated_uuid' => "mixed",
        'title'        => "array|null|string",
        'slug'         => "array|null|string"
    ])]
    private function prepareCategoryData(Store $request): array
    {
        return [
            'created_uuid' => $request->user()->uuid,
            'updated_uuid' => $request->user()->uuid,
            'title'        => $request->post('title'),
            'slug'         => $request->post('slug')
        ];
    }
}
