package study.securitybrowser;

import java.util.Map;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LabEndpoints {
    private final SyntheticCredentials credentials;

    public LabEndpoints(SyntheticCredentials credentials) {
        this.credentials = credentials;
    }

    @GetMapping("/browser/credentials/legacy")
    Map<String, Object> legacyMetadata() {
        // 教学观测面只暴露合成账号的算法标识/升级次数，绝不输出哈希、凭据或 token。
        return credentials.legacyMetadata();
    }

    @GetMapping({"/api/open", "/api/whoami", "/api/admin/report", "/browser/whoami", "/browser/admin/report", "/browser/sensitive", "/unlisted"})
    Map<String, Object> identity(HttpServletRequest request) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return Map.of("name", auth == null ? "none" : auth.getName(),
                "mechanism", auth == null ? "none" : auth.getClass().getSimpleName(),
                "preloginMarker", request.getSession(false) == null ? "absent"
                        : String.valueOf(request.getSession(false).getAttribute("lesson")),
                "requestThread", Thread.currentThread().getName());
    }

    @GetMapping("/browser/prelogin")
    Map<String, String> prelogin(HttpServletRequest request) {
        request.getSession(true).setAttribute("lesson", "lesson-u29");
        return Map.of("marker", "lesson-u29");
    }

    @GetMapping({"/browser/csrf", "/api/csrf"})
    Map<String, String> csrf(CsrfToken token) {
        return Map.of("token", token.getToken(), "headerName", token.getHeaderName(), "parameterName", token.getParameterName());
    }

    @PostMapping({"/browser/change", "/api/change"})
    Map<String, Object> change(HttpServletRequest request) {
        return identity(request);
    }

    @PostMapping("/browser/session/expire-soon")
    Map<String, Integer> expireSoon(HttpServletRequest request) {
        // 仅改变调用者自己的实验会话；CSRF 与认证仍由真实安全链强制执行。
        request.getSession(false).setMaxInactiveInterval(1);
        return Map.of("maxInactiveSeconds", 1);
    }
}
