<?php
/**
 * RFC 8414 and RFC 9728 metadata routes for OAuth resources.
 *
 * @package WPAgentCompanion
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/** @return array<string,mixed>|null RFC-8414/9728-Payload für einen Request-Pfad. */
function wpagent_companion_oauth_well_known_payload( string $request_uri ): ?array {
	$path          = untrailingslashit( (string) wp_parse_url( $request_uri, PHP_URL_PATH ) );
	$home_path     = untrailingslashit( (string) wp_parse_url( home_url(), PHP_URL_PATH ) );
	$resource_path = untrailingslashit( (string) wp_parse_url( wpagent_companion_oauth_mcp_resource(), PHP_URL_PATH ) );
	$rest_path     = untrailingslashit( (string) wp_parse_url( wpagent_companion_oauth_rest_resource(), PHP_URL_PATH ) );
	$authorization_paths = array(
		'/.well-known/oauth-authorization-server' . $home_path,
		$home_path . '/.well-known/oauth-authorization-server',
	);
	$protected_paths = array(
		'/.well-known/oauth-protected-resource' . $resource_path,
		$home_path . '/.well-known/oauth-protected-resource',
	);
	$rest_protected_paths = array(
		'/.well-known/oauth-protected-resource' . $rest_path,
		$home_path . '/.well-known/oauth-protected-resource/' . trim( rest_get_url_prefix(), '/' ),
	);
	if ( in_array( $path, array_unique( array_map( 'untrailingslashit', $rest_protected_paths ) ), true ) ) {
		return wpagent_companion_oauth_protected_resource_metadata( wpagent_companion_oauth_rest_resource() );
	}
	if ( in_array( $path, array_unique( array_map( 'untrailingslashit', $protected_paths ) ), true ) ) {
		return wpagent_companion_oauth_protected_resource_metadata();
	}
	if ( in_array( $path, array_unique( array_map( 'untrailingslashit', $authorization_paths ) ), true ) ) {
		return wpagent_companion_oauth_server_metadata();
	}
	return null;
}

/** Liefert RFC-8414/9728-Metadaten auch an den normativen Well-known-Pfaden. */
function wpagent_companion_oauth_well_known(): void {
	$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_unslash( $_SERVER['REQUEST_URI'] ) : '';
	$data        = wpagent_companion_oauth_well_known_payload( $request_uri );
	if ( null === $data ) {
		return;
	}
	nocache_headers();
	status_header( 200 );
	header( 'Content-Type: application/json; charset=utf-8' );
	header( 'X-Content-Type-Options: nosniff' );
	echo wp_json_encode( $data, JSON_UNESCAPED_SLASHES ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- JSON-Protokollantwort.
	exit;
}
add_action( 'template_redirect', 'wpagent_companion_oauth_well_known', 0 );
