<?php

namespace workfeed\config;

use Exception;
use traits\module_config_variable;

class workfeed_api_url_c
{
    use module_config_variable {
        validateVariableValue as private validateModuleConfigVariableValue;
    }

    private const TRUSTED_API_HOSTS = [
        'api.workfeed.io',
        'europe-west1-production-eu-327a3.cloudfunctions.net',
    ];

    /**
     * @throws Exception
     */
    public function __construct()
    {
        self::setupConfigVariable(
            'workfeed',
            'api_url',
            'string',
            true,
            null,
            'The base URL for the Workfeed API (trusted Workfeed endpoints only; see docs.workfeed.io)',
            'https://europe-west1-production-eu-327a3.cloudfunctions.net/api',
            false,
            'https://europe-west1-production-eu-327a3.cloudfunctions.net/api'
        );
    }

    public function validateVariableValue(mixed $value): bool
    {
        if (!$this->validateModuleConfigVariableValue($value)) {
            return false;
        }

        return self::isTrustedApiUrl((string)$value);
    }

    public static function isTrustedApiUrl(string $url): bool
    {
        $normalizedUrl = self::normalizeApiUrlForValidation($url);
        if (filter_var($normalizedUrl, FILTER_VALIDATE_URL) === false) {
            return false;
        }

        $parts = parse_url($normalizedUrl);

        if ($parts === false) {
            return false;
        }

        $scheme = strtolower((string)($parts['scheme'] ?? ''));
        $host = strtolower((string)($parts['host'] ?? ''));
        $port = $parts['port'] ?? null;

        return $scheme === 'https'
            && in_array($host, self::TRUSTED_API_HOSTS, true)
            && ($port === null || $port === 443)
            && !isset($parts['user'])
            && !isset($parts['pass']);
    }

    public static function normalizeApiUrlForValidation(string $url): string
    {
        $url = trim($url);

        if (preg_match('#^https?://#i', $url)) {
            return $url;
        }

        return 'https://' . ltrim($url, '/');
    }
}
