<?php

namespace Core\System;

class InstallerGuard
{
    /**
     * Resolve the project root safely even if ROOT_PATH
     * has not been defined yet during early bootstrap.
     */
    private static function rootPath(): string
    {
        return defined('ROOT_PATH')
            ? ROOT_PATH
            : dirname(__DIR__, 2);
    }

    public static function lockFile(): string
    {
        return self::rootPath() . '/storage/installed.lock';
    }

    public static function isInstalled(): bool
    {
        return is_file(self::lockFile());
    }

    public static function hasDatabaseConfig(): bool
    {
        Env::bootstrap(self::rootPath());

        return trim((string) Env::get('DB_HOST', '')) !== ''
            && trim((string) Env::get('DB_NAME', '')) !== ''
            && trim((string) Env::get('DB_USER', '')) !== '';
    }

    public static function canRunInstaller(): bool
    {
        if (Env::bool('INSTALLER_FORCE_ENABLE', false)) {
            return true;
        }

        if (self::isInstalled()) {
            return false;
        }

        return true;
    }

    public static function needsInstallation(): bool
    {
        return !self::isInstalled() && !self::hasDatabaseConfig();
    }

    public static function ensureLockFile(): void
    {
        $dir = dirname(self::lockFile());

        if (!is_dir($dir)) {
            @mkdir($dir, 0755, true);
        }

        if (!is_file(self::lockFile())) {
            @file_put_contents(self::lockFile(), 'installed=' . time() . PHP_EOL);
        }
    }
}
