<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\TaskBundle\Repository;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception;

class SingleTaskStateRepository
{
    private const FIND_ALL_STATES = <<<'SQL'
    SELECT DISTINCT jsonb_array_elements_text(current_states) FROM chill_task.single_task
    SQL;

    public function __construct(
        private readonly Connection $connection,
    ) {}

    /**
     * Return a list of all states associated to at least one single task in the database.
     *
     * @return list<string>
     *
     * @throws Exception
     */
    public function findAllExistingStates(): array
    {
        $states = [];

        foreach ($this->connection->fetchAllNumeric(self::FIND_ALL_STATES) as $row) {
            if ('' !== $row[0] && null !== $row[0]) {
                $states[] = $row[0];
            }
        }

        return $states;
    }
}
