package org.ta.authserver.controller;

import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsent;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 1.5.2 终极适配版：纯手动解析参数，无任何不存在的类
 */
@Controller
public class ConsentController {

    private final RegisteredClientRepository registeredClientRepository;
    private final OAuth2AuthorizationConsentService authorizationConsentService;

    // 仅注入核心依赖（无任何高阶解析类）
    public ConsentController(RegisteredClientRepository registeredClientRepository,
                             OAuth2AuthorizationConsentService authorizationConsentService) {
        this.registeredClientRepository = registeredClientRepository;
        this.authorizationConsentService = authorizationConsentService;
    }

    /**
     * 处理授权确认页请求（1.5.2 默认路径 /oauth2/consent）
     * 纯手动解析所有参数，无依赖任何不存在的类
     */
    @GetMapping("/oauth2/consent")
    public String consentPage(HttpServletRequest request, Model model) {
        // ========== 1. 纯手动提取所有授权请求参数（核心：适配1.5.2） ==========
        String clientId = request.getParameter("client_id"); // 客户端ID
        String responseType = request.getParameter("response_type"); // 响应类型（code）
        String redirectUri = request.getParameter("redirect_uri"); // 回调地址
        String scopeStr = request.getParameter("scope"); // 权限范围（read write）
        String state = request.getParameter("state"); // 状态码
        String codeChallenge = request.getParameter("code_challenge"); // PKCE挑战码
        String codeChallengeMethod = request.getParameter("code_challenge_method"); // PKCE方法

        // 校验核心参数（防止空指针）
        if (clientId == null || scopeStr == null) {
            return "error";
        }

        // ========== 2. 解析权限范围为Set集合 ==========
        Set<String> requestedScopes = new HashSet<>(Arrays.asList(scopeStr.split(" ")));

        // ========== 3. 获取当前登录用户名 ==========
        String principalName = request.getUserPrincipal().getName(); // 1.5.2 原生支持

        // ========== 4. 获取客户端信息 ==========
        RegisteredClient registeredClient = registeredClientRepository.findByClientId(clientId);
        if (registeredClient == null) {
            return "error";
        }

        // ========== 5. 获取已授权记录 ==========
        OAuth2AuthorizationConsent authorizationConsent = authorizationConsentService.findById(
                registeredClient.getId(), principalName);

        // ========== 6. 封装所有参数到页面（纯基础类型，无高阶类） ==========
        model.addAttribute("clientId", clientId);
        model.addAttribute("responseType", responseType);
        model.addAttribute("redirectUri", redirectUri);
        model.addAttribute("requestedScopes", requestedScopes);
        model.addAttribute("state", state);
        model.addAttribute("codeChallenge", codeChallenge);
        model.addAttribute("codeChallengeMethod", codeChallengeMethod);
        model.addAttribute("authorizationConsent", authorizationConsent);

        return "consent"; // 指向 static/consent.html
    }
}