<?php

declare(strict_types=1);

namespace apexl\Io\services;

use apexl\Config\ConfigurationInterface;
use apexl\Config\Exceptions\MissingConfigException;
use apexl\Vault\Vault;
use Exception;

final class InstallChecker
{
    public bool $isInstalled = false {
        /**
         * @throws Exception
         */
        get {
            if ($this->isInstalling) {
                return false;
            }

            if ($this->isInstalled) {
                return true;
            }

            try {
                if ($this->db->isInitialised()) {
                    /** Will throw exception if `sites` table does not exist */
                    $this->db->select('sites')->fields()->limit(1)->execute()->fetchAssoc();
                    $this->isInstalled = true;
                } else {
                    $this->isInstalled = false;
                }
            } catch (Exception $e) {
                $this->isInstalled = false;

                throw $e;
            }

            return $this->isInstalled;
        }
    }
    public bool $isInstalling = false;
    public bool $installRequired;
    public bool $onInstallPath;
    public string $installPath;

    /**
     * @throws MissingConfigException
     */
    public function __construct(private readonly Vault $db, HttpPaths $httpPaths, ConfigurationInterface $config)
    {
        $this->installRequired = $config->get('install.required');
        $this->installPath = $config->get('install.path');
        $this->onInstallPath = $httpPaths->getPath(0) !== $this->installPath;
    }

}