<?php

declare(strict_types=1);

namespace PortalPeople\sitesetup\services;

use Yii;

/**
 * SetupService
 *
 * Performs the one-time NGauge installation sequence.
 * Extracted from api/modules/v1/controllers/SiteController::actionSetup().
 *
 * The setup is idempotent: if the lock file already exists the method
 * returns immediately without executing any side effects.
 */
class SetupService
{
    /**
     * Path to the lock file that marks setup as complete.
     */
    private function lockFilePath(): string
    {
        return Yii::getAlias('@common') . '/config/setuprun.txt';
    }

    /**
     * Run the initial setup sequence.
     *
     * @param string $email  Administrator email address
     */
    public function runSetup(string $email): void
    {
        if (file_exists($this->lockFilePath())) {
            return;
        }

        \common\models\Schema::checkallschemas();

        $company = new \backend\models\Settings();
        $company->name = 'NGauge Demo';
        $company->nickname = Yii::$app->request->hostname;
        $company->is_default = 1;
        $company->save();

        \backend\models\Sysconfig::Generate($company->id);
        \backend\models\Defaults::applyDefaults();

        // Allow schema propagation before creating the admin user
        sleep(5);

        $user = new \backend\models\Signupform();
        $user->email = $email;
        $user->type = 'Global Admins';
        $user = $user->signup();
        $user->sendDirectAccount();

        file_put_contents($this->lockFilePath(), '1');
    }
}
