<?php

declare(strict_types=1);

namespace Plugin\tnt_mcp\src\Mcp\OAuth;

/**
 * Pure builders for the OAuth discovery documents the MCP connectors fetch before authorizing.
 * Kept free of any shop/HTTP dependency so the exact wire shapes are unit-testable. Mirrors the
 * podQuery saas-app gateway conventions (RFC 8414 authorization-server metadata + RFC 9728
 * protected-resource metadata) so the same ChatGPT/Claude connectors work unchanged.
 */
final class DiscoveryMetadata
{
    /**
     * RFC 8414 authorization-server metadata.
     *
     * @return array<string,mixed>
     */
    public static function authorizationServer(string $issuer): array
    {
        $base = rtrim($issuer, '/');

        return [
            'issuer'                                => $base,
            'authorization_endpoint'                => $base . '/tnt-mcp/authorize',
            'token_endpoint'                        => $base . '/tnt-mcp/token',
            'registration_endpoint'                 => $base . '/tnt-mcp/register',
            'response_types_supported'              => ['code'],
            'grant_types_supported'                 => ['authorization_code', 'refresh_token'],
            'token_endpoint_auth_methods_supported' => ['none', 'client_secret_basic', 'client_secret_post'],
            'code_challenge_methods_supported'      => ['S256'],
            'scopes_supported'                      => ScopeCatalog::all(),
        ];
    }

    /**
     * RFC 9728 protected-resource metadata. `resource` echoes the host the connector actually hit
     * (so it matches whatever domain fronts the shop); `authorization_servers` points at the issuer.
     *
     * @return array<string,mixed>
     */
    public static function protectedResource(string $resource, string $issuer): array
    {
        return [
            'resource'                 => rtrim($resource, '/'),
            'authorization_servers'    => [rtrim($issuer, '/')],
            'bearer_methods_supported' => ['header'],
            'scopes_supported'         => ScopeCatalog::all(),
        ];
    }

    /**
     * The `WWW-Authenticate` challenge value returned on a 401 from the MCP endpoint, pointing the
     * connector at the protected-resource metadata so it can discover the authorization server.
     */
    public static function challenge(string $resourceMetadataUrl): string
    {
        return sprintf('Bearer resource_metadata="%s"', $resourceMetadataUrl);
    }
}
