<?php

declare(strict_types=1);

$legacyRoot = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR;

if (!defined('WD')) {
    define('WD', $legacyRoot);
}

chdir(rtrim(WD, DIRECTORY_SEPARATOR));

$legacyDefaults = [
    'USE_ENV' => 'true',
    'DEBUG' => 'true',
    'ENCRYPTION_KEY' => 'ci-test-encryption-key',
    'CORS' => '*',
    'CONFIG_TIMEZONE' => 'Europe/Copenhagen',
    'CONFIG_DB_TARGET' => 'debug',
    'CONFIG_DB_HOST' => 'mysql-debug',
    'CONFIG_DB_USER' => 'root',
    'CONFIG_DB_PASSWORD' => 'debug_root_password',
    'CONFIG_DB_DATABASE' => 'nnks_db_debug',
    'CONFIG_DB_PORT' => '3306',
    'CONFIG_DB_DEBUG_HOST' => 'mysql-debug',
    'CONFIG_DB_DEBUG_USER' => 'root',
    'CONFIG_DB_DEBUG_PASSWORD' => 'debug_root_password',
    'CONFIG_DB_DEBUG_DATABASE' => 'nnks_db_debug',
    'CONFIG_DB_DEBUG_PORT' => '3306',
    'REDIS_CONFIG_HOST' => 'redis',
    'REDIS_CONFIG_USER' => 'default',
    'REDIS_CONFIG_DATABASE' => '0',
    'REDIS_CONFIG_PASSWORD' => '',
    'REDIS_CONFIG_PORT' => '6379',
    'REDIS_CONFIG_DEBUG_HOST' => 'redis',
    'REDIS_CONFIG_DEBUG_USER' => 'default',
    'REDIS_CONFIG_DEBUG_DATABASE' => '0',
    'REDIS_CONFIG_DEBUG_PASSWORD' => '',
    'REDIS_CONFIG_DEBUG_PORT' => '6379',
    'ECONOMIC_API_APP_ACCESS_GRANT' => 'ci-test',
    'ECONOMIC_API_APP_ACCESS_GRANT2' => 'ci-test-secondary',
    'ECONOMIC_API_APP_SECRET_TOKEN' => 'ci-test-secret',
    'WORDPRESS_STATIC_TOKEN' => 'ci-test',
    'EMAIL_WASH_CERTIFICATE_TOKEN' => 'ci-test',
    'WORDPRESS_API_URL' => 'http://localhost',
    'MINIO_ENDPOINT' => '',
    'MINIO_ACCESS_KEY' => '',
    'MINIO_SECRET_KEY' => '',
    'SLACK_DEFAULT_WEBHOOK' => '',
    'EDGE_BROKER_SHARED_SECRET' => 'truckwash-edge-ci',
    'EDGE_GATEWAY_VIEW_CACHE_TTL' => '0',
    'TRUCKWASH_TEST_BLOCK_REAL_SHELLY' => '1',
];

foreach ($legacyDefaults as $key => $value) {
    if (getenv($key) !== false) {
        continue;
    }

    putenv($key . '=' . $value);
    $_ENV[$key] = $value;
    $_SERVER[$key] = $value;
}

require_once WD . 'vendor/autoload.php';
require_once WD . 'config.php';

if (getenv('API_TEST_BOOTSTRAP_SCHEMA') === '1') {
    require_once WD . 'tests/Support/Api/ApiSchemaBootstrap.php';

    $schemaDb = new mysqli(
        getenv('CONFIG_DB_HOST') ?: 'mysql-debug',
        getenv('CONFIG_DB_USER') ?: 'root',
        getenv('CONFIG_DB_PASSWORD') ?: 'debug_root_password',
        getenv('CONFIG_DB_DATABASE') ?: 'nnks_db_debug',
        (int)(getenv('CONFIG_DB_PORT') ?: 3306)
    );

    if ($schemaDb->connect_errno) {
        fwrite(STDERR, 'Unable to bootstrap legacy schema: ' . $schemaDb->connect_error . PHP_EOL);
        exit(1);
    }

    (new Tests\Support\Api\ApiSchemaBootstrap($schemaDb))->ensureSchema();
    $schemaDb->close();
}

if (!isset($GLOBALS['db']) || !$GLOBALS['db'] instanceof classes\db) {
    $GLOBALS['db'] = new classes\db($GLOBALS['CONFIG_DB']);
    $GLOBALS['db']->connect();
}

$GLOBALS['db']->query("
    INSERT INTO departments (id, name, visible, archived)
    VALUES (1, 'CI Self-Serve Department', 1, 0)
    ON DUPLICATE KEY UPDATE
        name = VALUES(name),
        visible = VALUES(visible),
        archived = VALUES(archived)
");
$GLOBALS['db']->query("
    INSERT INTO department_lanes (id, department, name, relay_machine_id, selfserve_enabled)
    VALUES (1, 1, 'CI Lane', 'demo-machine-relay', 1)
    ON DUPLICATE KEY UPDATE
        department = VALUES(department),
        name = VALUES(name),
        relay_machine_id = VALUES(relay_machine_id),
        selfserve_enabled = VALUES(selfserve_enabled),
        deleted_at = NULL
");
$GLOBALS['db']->query("
    DELETE FROM department_variables
    WHERE department_id = 1
      AND variable = 'selfserve_enabled'
");
$GLOBALS['db']->query("
    INSERT INTO department_variables (department_id, variable, value)
    VALUES (1, 'selfserve_enabled', 'true')
");

if (!defined('redis')) {
    try {
        define('redis', (new classes\redis())->connect());
    } catch (Throwable $throwable) {
        fwrite(STDERR, 'Unable to connect Redis for legacy test bootstrap: ' . $throwable->getMessage() . PHP_EOL);
        exit(1);
    }
}
