package cn.nianxx.thhotel.platform.identity.control;

import cn.nianxx.thhotel.platform.identity.common.request.AuthLoginRequest;
import cn.nianxx.thhotel.platform.identity.common.result.AuthLoginResult;
import cn.nianxx.thhotel.platform.identity.common.result.AuthLogoutResult;
import cn.nianxx.thhotel.platform.identity.common.result.AuthMeResult;
import cn.nianxx.thhotel.platform.identity.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录权限 Controller。提供登录、登出和当前用户上下文接口。
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final AuthService authService;

    /**
     * 注入登录认证服务，Controller 只负责 HTTP 参数转换。
     */
    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    /**
     * 用户名密码登录，成功后返回 Bearer token 和当前用户上下文。
     */
    @PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public AuthLoginResult login(
            @Valid @RequestBody AuthLoginRequest request,
            HttpServletRequest servletRequest) {
        return authService.login(request, servletRequest);
    }

    /**
     * 获取当前登录用户、权限、酒店和菜单上下文。
     */
    @GetMapping(value = "/me", produces = MediaType.APPLICATION_JSON_VALUE)
    public AuthMeResult currentUser(
            @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        return authService.currentUser(authorizationHeader);
    }

    /**
     * 登出当前 token，撤销当前数据库 session。
     */
    @PostMapping(value = "/logout", produces = MediaType.APPLICATION_JSON_VALUE)
    public AuthLogoutResult logout(
            @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        return authService.logout(authorizationHeader);
    }
}
