<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\DataSource\JDisc;

use idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\DataSource\DataSource;
use idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\Option\SelectOptionValue;
use isys_exception_general;
use isys_jdisc_dao;

class JDiscGroupDataSource implements DataSource
{
    /**
     * @param isys_jdisc_dao $dao
     */
    public function __construct(private isys_jdisc_dao $dao)
    {
    }

    /**
     * @param array $parameters
     * @return array|SelectOptionValue[]
     * @throws isys_exception_general
     */
    public function getValues(array $parameters): array
    {
        if (empty($parameters['server'])) {
            return [];
        }
        $this->dao->switch_database($parameters['server']);
        $groups = $this->dao->get_jdisc_groups();
        $values = array_map(
            fn (mixed $data) => new SelectOptionValue(
                "{$data['id']}",
                $data['name']
            ),
            $groups ?: [],
        );

        return array_values($values);
    }
}