<?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';

$results = [];
$results['boolean_true'] = normalizeAppSettingValue('on', ['type' => 'boolean']) === true;
$results['boolean_false'] = normalizeAppSettingValue('0', ['type' => 'boolean']) === false;
$results['integer'] = normalizeAppSettingValue('1905', ['type' => 'integer']) === 1905;
$results['integer_csv'] = normalizeAppSettingValue('227, 233 / 245', [
    'type' => 'csv',
    'item_type' => 'integer',
]) === [227, 233, 245];
$results['lines'] = normalizeAppSettingValue("Первое\n\nВторое", ['type' => 'lines']) === ['Первое', 'Второе'];

$fields = appSettingsFieldsByKey();
foreach (['OPENAI_API_KEY', 'DEAL_PHONE_FIELD', 'TECHNIQUE_QUALIFIED_STAGE_ID', 'FOLLOWUP_DELAY_SECONDS', 'FOLLOWUP_MESSAGE', 'FOLLOWUP_OFFSETS_SECONDS'] as $key) {
    $results['schema_' . strtolower($key)] = isset($fields[$key]);
}

$uiValues = currentAppSettingsForUi();
$results['openai_key_masked'] = ($uiValues['OPENAI_API_KEY']['value'] ?? null) === '';
$results['client_secret_masked'] = ($uiValues['BITRIX_CLIENT_SECRET']['value'] ?? null) === '';

$temporaryPath = sys_get_temp_dir() . '/darex-app-settings-' . bin2hex(random_bytes(5)) . '.php';
$fixture = ['version' => 1, 'values' => ['OPENAI_MODEL' => 'test-model']];
writeAppSettingsFile($temporaryPath, $fixture);
$loaded = require $temporaryPath;
$results['settings_file_roundtrip'] = $loaded === $fixture;
$results['portal_admin_boolean'] = isBitrixPortalAdministrator(['ADMIN' => true]);
$results['portal_admin_y'] = isBitrixPortalAdministrator(['ADMIN' => 'Y']);
$results['regular_user_not_admin'] = !isBitrixPortalAdministrator(['ADMIN' => false]);
$results['user_admin_boolean_result'] = isTruthyBitrixValue(true);
$results['user_admin_y_result'] = isTruthyBitrixValue('Y');
$results['user_admin_false_result'] = !isTruthyBitrixValue(false);
@unlink($temporaryPath);

$failed = in_array(false, $results, true);
echo json_encode([
    'ok' => !$failed,
    'results' => $results,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;

exit($failed ? 1 : 0);
