<?php

declare(strict_types=1);

function security_store_file(): string
{
    return __DIR__ . '/app_security.json';
}

function security_store_default_token(): string
{
    return 'THEFULL_APP_TAvh_K3Ddn3cTpFhYUH60CCrgkywj_Ba_Z7pvF2zXr0';
}

function security_store_clean_token(?string $token): string
{
    $token = trim((string)$token);
    $token = preg_replace('/[^A-Za-z0-9_\-\.\:]/', '', $token) ?: '';
    if (strlen($token) < 24) {
        return '';
    }
    if (strlen($token) > 160) {
        return substr($token, 0, 160);
    }
    return $token;
}

function security_store_load(): array
{
    $file = security_store_file();
    if (!is_file($file)) {
        return [];
    }
    $raw = @file_get_contents($file);
    if (!is_string($raw) || trim($raw) === '') {
        return [];
    }
    $json = json_decode($raw, true);
    return is_array($json) ? $json : [];
}

function security_store_token(): string
{
    $json = security_store_load();
    $token = security_store_clean_token($json['app_token'] ?? '');
    return $token !== '' ? $token : security_store_default_token();
}

function security_store_save_token(string $token): bool
{
    $token = security_store_clean_token($token);
    if ($token === '') {
        return false;
    }
    $payload = [
        'ok' => true,
        'app_token' => $token,
        'updated_at' => (int) round(microtime(true) * 1000),
        'token_header' => 'X-App-Token',
        'token_query' => 'app_token'
    ];
    $json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    if (!is_string($json)) {
        return false;
    }
    $file = security_store_file();
    $tmp = $file . '.tmp';
    if (@file_put_contents($tmp, $json, LOCK_EX) === false) {
        return false;
    }
    return @rename($tmp, $file);
}

function security_store_generate_token(): string
{
    try {
        return 'THEFULL_APP_' . rtrim(strtr(base64_encode(random_bytes(32)), '+/', '_-'), '=');
    } catch (Throwable $e) {
        return 'THEFULL_APP_' . sha1(uniqid('', true) . microtime(true));
    }
}
