<?php

namespace LaraBB\Settings\Actions\Prefix;

use Exception;
use Illuminate\Database\Connection;
use LaraBB\Settings\Tasks\Prefix\DestroyTask as DestroyPrefixTask;
use LaraBB\Settings\Tasks\Prefix\FindTask as FindPrefixTask;
use LaraBB\Settings\UI\Web\Requests\Prefix\Destroy;
use Throwable;

/**
 * Class DestroyAction
 * @package LaraBB\Settings\Actions\Prefix
 */
class DestroyAction
{
    /**
     * DestroyAction constructor.
     * @param FindPrefixTask $findPrefixTask
     * @param DestroyPrefixTask $destroyPrefixTask
     * @param Connection $connection
     */
    public function __construct(
        private readonly FindPrefixTask $findPrefixTask,
        private readonly DestroyPrefixTask $destroyPrefixTask,
        private readonly Connection $connection
    ) {

    }

    /**
     * @param Destroy $request
     * @return bool|null
     * @throws Exception
     */
    public function run(Destroy $request): ?bool
    {
        $prefix = $this->findPrefixTask->byUuid($request->post('uuid'));

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

        return true;
    }
}
