<?php

declare(strict_types=1);

namespace apexl\Io\services;

use apexl\Io\modules\install\services\databaseTools;
use apexl\Vault\Vault;
use Exception;

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

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

            // First check if the database exists:
            $this->isInstalled = $this->databaseTools->checkDBExists();

            // Next check if a core table exists
            if ($this->isInstalled) {
                try {
                    if ($this->db->isInitialised()) {
                        /** Will throw exception if `sites` table does not exist */
                        $this->db->select('sites')->fields()->limit(1)->execute()->fetchAssoc();
                    } 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;

    public function __construct(private readonly Vault $db, private readonly databaseTools $databaseTools, HttpPaths $httpPaths)
    {
        $this->installRequired = config('app.install.required', true);
        $this->installPath = config('app.install.path') ?: 'install';
        $this->onInstallPath = $httpPaths->getPath(0) !== $this->installPath;
    }

}