<?php

declare(strict_types=1);

namespace apexl\Io\modules\system\services;

use apexl\Io\services\InstallChecker;
use apexl\Vault\Vault;

/**
 * @Todo Add cache for found modules
 */
final readonly class ModuleFinder
{

    public function __construct(private Vault $database, private InstallChecker $installChecker) {}

    public function all(): array
    {
        if ($this->installChecker->isInstalled) {
            return $this->fetchModulesFromDb(false);
        }

        return [];
    }

    private function fetchModulesFromDb(bool $installed = true): array
    {
        $query = $this->database
            ->select('modules')
            ->fields(['module'])
            ->orderBy('weight');

        if ($installed) {
            $query->where('installed', 1);
        }
            
        $result = $query
            ->execute()
            ->fetchAllAssoc('module');

        return array_column($result, 'module');
    }

    public function installed(): array
    {
        if ($this->installChecker->isInstalled) {
            return $this->fetchModulesFromDb();
        }

        return [];
    }
}
