<?php
declare(strict_types=1);

function env_value(string $name, ?string $default = null): ?string
{
    $value = getenv($name);
    return $value === false ? $default : $value;
}

function env_int(string $name, int $default): int
{
    $value = env_value($name);
    return $value === null || $value === '' ? $default : (int) $value;
}

function env_bool(string $name, bool $default = false): bool
{
    $value = env_value($name);
    if ($value === null || $value === '') {
        return $default;
    }
    return filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? $default;
}

return [
    'environment' => env_value('APP_ENV', 'production'),
    'app_key' => env_value('APP_KEY', ''),
    'db' => [
        'host' => env_value('DB_HOST', 'localhost'),
        'port' => env_int('DB_PORT', 3306),
        'name' => env_value('DB_NAME', ''),
        'user' => env_value('DB_USER', ''),
        'pass' => env_value('DB_PASS', ''),
        'charset' => 'utf8mb4',
    ],
    'app' => [
        'site_url' => rtrim((string) env_value('APP_URL', ''), '/'),
        'trial_days' => env_int('TRIAL_DAYS', 7),
        'paid_days' => env_int('PAID_DAYS', 30),
        'portal_token_minutes' => env_int('PORTAL_TOKEN_MINUTES', 30),
        'proxy_token_minutes' => env_int('PROXY_TOKEN_MINUTES', 360),
        'max_playlists' => env_int('MAX_PLAYLISTS', 10),
        'allow_legacy_device_claim' => env_bool('ALLOW_LEGACY_DEVICE_CLAIM', false),
        'cors_origins' => array_values(array_filter(array_map('trim', explode(',', (string) env_value('CORS_ORIGINS', '*'))))),
    ],
    'admin' => [
        'username' => env_value('ADMIN_USERNAME', 'admin'),
        'password_hash' => env_value('ADMIN_PASSWORD_HASH', ''),
    ],
    'stripe' => [
        'secret_key' => env_value('STRIPE_SECRET_KEY', ''),
        'webhook_secret' => env_value('STRIPE_WEBHOOK_SECRET', ''),
        'currency' => strtolower((string) env_value('STRIPE_CURRENCY', 'usd')),
        'amount_cents' => env_int('STRIPE_AMOUNT_CENTS', 1000),
        'product_name' => env_value('STRIPE_PRODUCT_NAME', 'Nexo Player activation'),
    ],
    'proxy' => [
        'external_hosts' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env_value(
            'PROXY_EXTERNAL_HOSTS',
            'www.imdb.com,www.themoviedb.org,image.tmdb.org,opensubtitles-v3.strem.io,v3-cinemeta.strem.io,cinemeta-live.strem.io,r.jina.ai'
        )))))),
        'max_text_bytes' => env_int('PROXY_MAX_TEXT_BYTES', 8 * 1024 * 1024),
    ],
];
