<?php

declare(strict_types=1);

final class MyronMcpOAuthMetadataService
{
    public function issuer(): string
    {
        return myronAppUrl();
    }

    public function resource(): string
    {
        return myronAppUrl() . myronAdminBasePath() . '/mcp';
    }

    public function protectedResourceMetadataUrl(): string
    {
        return myronAppUrl() . '/.well-known/oauth-protected-resource';
    }

    /**
     * @return array<string, mixed>
     */
    public function protectedResourceMetadata(): array
    {
        return [
            'resource' => $this->resource(),
            'authorization_servers' => [$this->issuer()],
            'bearer_methods_supported' => ['header'],
            'resource_documentation' => myronAppUrl() . myronBuildAdminUrl('administration.aiConnections'),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public function authorizationServerMetadata(): array
    {
        $issuer = $this->issuer();
        $metadata = [
            'issuer' => $issuer,
            'authorization_endpoint' => $issuer . '/oauth/authorize',
            'token_endpoint' => $issuer . '/oauth/token',
            'response_types_supported' => ['code'],
            'grant_types_supported' => ['authorization_code', 'refresh_token'],
            'token_endpoint_auth_methods_supported' => ['client_secret_basic', 'client_secret_post'],
            'code_challenge_methods_supported' => ['S256'],
            'scopes_supported' => MyronApiScopes::ALL_BASE,
            'resource_indicators_supported' => true,
        ];

        if ($this->dynamicClientRegistrationEnabled()) {
            $metadata['registration_endpoint'] = $issuer . '/oauth/register';
        }

        return $metadata;
    }

    private function dynamicClientRegistrationEnabled(): bool
    {
        return in_array(strtolower(trim((string) (getenv('MYRON_MCP_OAUTH_DCR_ENABLED') ?: ''))), ['1', 'true', 'yes', 'on'], true);
    }
}
