<?php

namespace LaraBB\Category\Actions\Admin;

use Exception;
use Illuminate\Database\Connection;
use LaraBB\Category\Tasks\DestroyTask as DestroyCategoryTask;
use LaraBB\Category\Tasks\FindTask as FindCategoryTask;
use LaraBB\Category\UI\Web\Requests\Destroy;
use Throwable;

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

    /**
     * @param Destroy $request
     * @return bool|null
     * @throws Exception
     */
    public function run(Destroy $request): ?bool
    {
        $category = $this->findCategoryTask->byUuid($request->post('uuid'));
        try {
            $this->connection->transaction(function() use($category) {
                $this->destroyCategoryTask->run($category);
            });
        } catch(Throwable $t) {
            return false;
        }

        return true;
    }
}
