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

import cn.meowrain.aioj.backend.auth.dto.req.UserLoginRequestDTO;
import cn.meowrain.aioj.backend.auth.dto.resp.UserAuthRespDTO;
import cn.meowrain.aioj.backend.auth.dto.resp.UserLoginResponseDTO;
import cn.meowrain.aioj.backend.auth.oauth2.service.OAuth2SessionService;
import cn.meowrain.aioj.backend.auth.service.AuthService;

import cn.meowrain.aioj.backend.framework.core.web.Result;
import cn.meowrain.aioj.backend.framework.core.web.Results;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
@RequestMapping("/v1/auth")
public class AuthController {

	private final AuthService authService;

	private final OAuth2SessionService sessionService;

	@PostMapping("/login")
	public Result<UserLoginResponseDTO> login(@RequestBody UserLoginRequestDTO userLoginRequest) {
		UserLoginResponseDTO userLoginResponse = authService.userLogin(userLoginRequest);
		return Results.success(userLoginResponse);

	}

	@PostMapping("/refresh")
	public Result<UserLoginResponseDTO> refresh(@RequestParam String refreshToken) {
		return Results.success(authService.refreshToken(refreshToken));
	}

	@PostMapping("/auth")
	public Result<String> auth(@RequestBody UserLoginRequestDTO userLoginRequest) {
		UserLoginResponseDTO userLoginResponseDTO = authService.userLogin(userLoginRequest);
		return Results.success(userLoginResponseDTO.getAccessToken());
	}

	@PostMapping("/validate")
	public Result<Boolean> validate(@RequestHeader(value = "Authorization", required = false) String authorization) {
		// 从Authorization头中提取Bearer token
		String token = null;
		if (authorization != null && authorization.startsWith("Bearer ")) {
			token = authorization.substring(7);
		}

		// 检查Token黑名单
		if (token != null && sessionService.isTokenBlacklisted(token)) {
			return Results.success(false);
		}

		Boolean isValid = authService.validateToken(token);
		return Results.success(isValid);
	}

	@GetMapping("/getUserInfo")
	public Result<UserAuthRespDTO> getUserInfo() {

		return Results.success(authService.getUserInfo());
	}

}
