<?php

namespace LaraBB\User\Actions\Admin;

use Exception;
use Illuminate\Database\Connection;
use LaraBB\User\Tasks\DestroyTask as DestroyUserTask;
use LaraBB\User\Tasks\FindTask as FindUserTask;
use LaraBB\User\UI\Web\Requests\Destroy;
use Throwable;

/**
 * Class DestroyAction
 * @package LaraBB\User\Actions\Admin
 */
class DestroyAction
{
    /**
     * DestroyAction constructor.
     * @param FindUserTask $findUserTask
     * @param DestroyUserTask $destroyUserTask
     * @param Connection $db
     */
    public function __construct(
        private readonly FindUserTask $findUserTask,
        private readonly DestroyUserTask $destroyUserTask,
        private readonly Connection $db
    ) {

    }

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

        try {
            $this->db->transaction(function () use ($user) {
                $this->destroyUserTask->run($user);
            });
        } catch (Throwable $t) {
            return false;
        }

        return true;
    }
}
