<?php
declare(strict_types=1);
namespace PpPhp\Generated\SocialAuth;

abstract class AbstractProvider implements ProviderInterface
{
    public function __construct(protected array $config) {}
    protected function value(string $key, string $env = ''): string { $fromEnv = $env !== '' ? getenv($env) : false; return trim((string)($fromEnv !== false && $fromEnv !== '' ? $fromEnv : ($this->config[$key] ?? ''))); }
    protected function callbackUri(): string
    {
        $configured = $this->value('redirect_uri'); if ($configured !== '') return $configured;
        $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
        $host = (string)($_SERVER['HTTP_HOST'] ?? 'localhost');
        return ($https ? 'https' : 'http') . '://' . $host . (defined('APP_BASE') ? APP_BASE : '') . '/generated/auth/social/' . $this->id() . '/callback.php';
    }
    protected function query(string $url, array $params): string { return $url . '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986); }
    protected function failOnProviderError(array $request): void { if (!empty($request['error'])) throw new \RuntimeException((string)($request['error_description'] ?? $request['error'])); }
    protected function token(string $url, array $params): array { return HttpClient::post($url, $params); }
    protected function verified(mixed $value): bool { return $value === true || $value === 1 || $value === 'true' || $value === '1'; }
}
