package cn.meowrain.aioj.backend.auth.oauth2.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * OAuth2 Well-Known 配置端点（OIDC Discovery） 返回 OAuth2/OIDC 服务器的元数据配置
 *
 * @author meowrain
 * @since 2025-12-14
 */
@RestController
@RequestMapping("/.well-known")
@RequiredArgsConstructor
@Tag(name = "OAuth2 Well-Known 端点", description = "OIDC Discovery 相关接口")
public class OAuth2WellKnownController {

	// TODO: 从配置文件读取这些值
	private static final String ISSUER = "http://localhost:10011/api";

	/**
	 * OIDC Discovery 端点
	 * @return OIDC 配置元数据
	 */
	@GetMapping("/openid-configuration")
	@Operation(summary = "OIDC Discovery", description = "返回 OpenID Connect 配置元数据")
	public Map<String, Object> openidConfiguration() {
		Map<String, Object> config = new HashMap<>();

		// 1. 基本信息
		config.put("issuer", ISSUER);

		// 2. 端点 URL
		config.put("authorization_endpoint", ISSUER + "/oauth2/authorize");
		config.put("token_endpoint", ISSUER + "/oauth2/token");
		config.put("userinfo_endpoint", ISSUER + "/oauth2/userinfo");
		config.put("end_session_endpoint", ISSUER + "/oauth2/logout");
		config.put("jwks_uri", ISSUER + "/oauth2/jwks"); // TODO: 实现 JWKS 端点

		// 3. 支持的响应类型
		config.put("response_types_supported", List.of("code"));

		// 4. 支持的授权类型
		config.put("grant_types_supported", List.of("authorization_code", "refresh_token"));

		// 5. 支持的 Subject 类型
		config.put("subject_types_supported", List.of("public"));

		// 6. 支持的 ID Token 签名算法
		config.put("id_token_signing_alg_values_supported", List.of("HS256"));

		// 7. 支持的作用域
		config.put("scopes_supported", List.of("openid", "profile", "email"));

		// 8. 支持的 Token 端点认证方法
		config.put("token_endpoint_auth_methods_supported", List.of("client_secret_post", "client_secret_basic"));

		// 9. 支持的 PKCE 方法
		config.put("code_challenge_methods_supported", List.of("S256", "plain"));

		// 10. 支持的 Claims
		config.put("claims_supported",
				List.of("sub", "name", "preferred_username", "email", "email_verified", "picture", "role"));

		// 11. 其他配置
		config.put("response_modes_supported", List.of("query", "fragment"));
		config.put("request_parameter_supported", false);
		config.put("request_uri_parameter_supported", false);
		config.put("require_request_uri_registration", false);

		return config;
	}

}
