<?php

declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit(1);
}

require_once __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/settings.php';

$options = getopt('', ['force', 'help']);
if (isset($options['help'])) {
    echo "Usage: php tools/migrate_settings.php [--force]\n";
    exit(0);
}

$settingsPath = (string) config('APP_SETTINGS_FILE');
if (is_file($settingsPath) && !isset($options['force'])) {
    fwrite(STDERR, "Settings already exist. Use --force to refresh them from the effective configuration.\n");
    exit(1);
}

$values = [];
foreach (appSettingsFieldsByKey() as $key => $field) {
    $values[$key] = config($key, $field['default']);
}

$saved = saveAppSettings($values, [
    'ID' => 'cli',
    'NAME' => 'CLI migration',
    'LAST_NAME' => '',
]);

echo json_encode([
    'ok' => true,
    'settings_file' => $settingsPath,
    'saved_keys' => count($saved['values']),
    'updated_at' => $saved['updated_at'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
