<?php

namespace LaraBB\Category\Actions\Admin;

use Illuminate\Database\Connection;
use JetBrains\PhpStorm\ArrayShape;
use LaraBB\Category\Tasks\FindTask as FindCategoryTask;
use LaraBB\Category\Tasks\UpdateTask as UpdateCategoryTask;
use LaraBB\Category\UI\Web\Requests\Update;
use Throwable;

/**
 * Class UpdateAction
 * @package LaraBB\Category\Actions\Admin
 */
class UpdateAction
{
    /**
     * UpdateAction constructor.
     * @param FindCategoryTask $findCategoryTask
     * @param UpdateCategoryTask $updateCategoryTask
     * @param Connection $connection
     */
    public function __construct(
        private readonly FindCategoryTask $findCategoryTask,
        private readonly UpdateCategoryTask $updateCategoryTask,
        private readonly Connection $connection
    ) {
    }

    /**
     * @param Update $request
     * @return bool
     */
    public function run(Update $request): bool
    {
        $category = $this->findCategoryTask->byUuid($request->post('uuid'));
        try {
            $this->connection->transaction(function () use ($category, $request) {
                $this->updateCategoryTask->run($category, $this->prepareCategoryData($request));
            });
        } catch (Throwable $t) {
            return false;
        }

        return true;
    }

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