<?php

declare(strict_types=1);

require_once __DIR__ . '/support.php';

$options = scripts_parse_options($argv);
$forceEnv = isset($options['force-env']);
$prepareEnv = $forceEnv || isset($options['prepare-env']) || !is_file(scripts_env_path());

scripts_stdout('Starte SaaS-Installationsvorbereitung...');
scripts_stdout('');

require __DIR__ . '/check-prerequisites.php';

if ($prepareEnv) {
    $envValues = scripts_read_env_file(scripts_env_example_path());
    try {
        scripts_write_env_file($envValues, scripts_env_path());
        scripts_stdout('Lokale .env wurde angelegt: ' . scripts_env_path());
    } catch (Throwable $exception) {
        scripts_stderr($exception->getMessage());
    }

    if ($forceEnv) {
        scripts_stdout('Hinweis: vorhandene .env wurde bewusst ueberschrieben.');
    }
}

try {
    $envValues = scripts_read_env_file(scripts_env_path());
    $dbConnection = scripts_normalize_db_connection($envValues['DB_CONNECTION'] ?? 'mysql');
    $bundlePath = scripts_build_migration_bundle(null, $dbConnection);
} catch (Throwable $exception) {
    scripts_stderr($exception->getMessage());
}

scripts_stdout('');
scripts_stdout('SQL-Bundle fuer ' . scripts_connection_label($dbConnection) . ' erzeugt: ' . $bundlePath);
scripts_stdout('Naechste Schritte:');
scripts_stdout('1. saas-app/.env mit echten DB-, Mail- und Tenancy-Werten fuellen.');
scripts_stdout('2. Das SQL-Bundle manuell importieren oder `php scripts/run-sql-migrations.php --connection=' . $dbConnection . ' --server=... --database=...` verwenden.');
scripts_stdout('3. Danach ersten Tenant, ersten Benutzer und erste Member-Zuordnung anlegen.');
