package com.heaerie.server.auth201.Auth201Server.controller;

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class UserController {

    /**
     * Endpoint to get user information (protected resource)
     * Requires a valid access token
     */
    @GetMapping("/userinfo")
    public Map<String, Object> userInfo(@AuthenticationPrincipal Jwt jwt) {
        return Map.of(
            "sub", jwt.getSubject(),
            "username", jwt.getClaimAsString("sub"),
            "scopes", jwt.getClaimAsStringList("scope"),
            "exp", jwt.getExpiresAt(),
            "iat", jwt.getIssuedAt()
        );
    }

    /**
     * Public endpoint to check server status
     */
    @GetMapping("/")
    public Map<String, String> home() {
        return Map.of(
            "message", "OAuth 2.1 Authorization Server is running",
            "wellKnown", "http://localhost:9000/.well-known/oauth-authorization-server"
        );
    }
}

/**
 * OAuth 2.1 Callback Controller
 * Handles the authorization callback and displays the result
 */
@Controller
class CallbackController {

    /**
     * OAuth 2.1 Authorization Callback Endpoint
     * This endpoint receives the authorization code after successful authentication
     */
    @GetMapping("/authorized")
    public String authorized(
        @RequestParam(required = false) String code,
        @RequestParam(required = false) String state,
        @RequestParam(required = false) String error,
        @RequestParam(required = false) String error_description,
        Model model
    ) {
        model.addAttribute("code", code);
        model.addAttribute("state", state);
        model.addAttribute("error", error);
        model.addAttribute("errorDescription", error_description);
        model.addAttribute("hasError", error != null);
        model.addAttribute("tokenEndpoint", "http://localhost:9000/oauth2/token");
        
        return "authorized";
    }

    /**
     * Logged out callback endpoint
     */
    @GetMapping("/logged-out")
    public String loggedOut(Model model) {
        model.addAttribute("message", "You have been successfully logged out");
        return "logged-out";
    }
}
