package com.emotion.controller;

import com.emotion.common.Result;
import com.emotion.dto.response.UserInfoResponse;
import com.emotion.service.TokenService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Token控制器
 * 提供基于请求头Authorization的token验证和用户信息获取功能
 *
 * @author huazhongmin
 * @date 2025-07-23
 */
@RestController
@RequestMapping("/token")
@Tag(name = "Token管理", description = "Token验证和用户信息获取")
public class TokenController {

    @Autowired
    private TokenService tokenService;

    /**
     * 通过请求头中的token获取用户信息
     * Token应该在请求头中以 "Authorization: Bearer {token}" 的形式传递
     */
    @GetMapping("/user-info")
    @Operation(summary = "获取用户信息", description = "通过请求头中的token获取当前用户信息")
    public Result<UserInfoResponse> getUserInfoByToken(HttpServletRequest request) {
        UserInfoResponse userInfo = tokenService.getUserInfoByToken(request);
        return Result.success(userInfo);
    }

    /**
     * 通过请求头中的token获取用户名
     * Token应该在请求头中以 "Authorization: Bearer {token}" 的形式传递
     */
    @GetMapping("/username")
    @Operation(summary = "获取用户名", description = "通过请求头中的token获取当前用户名")
    public Result<String> getUsernameByToken(HttpServletRequest request) {
        String username = tokenService.getUsernameByToken(request);
        return Result.success(username);
    }

    /**
     * 验证请求头中的token并返回用户ID
     * Token应该在请求头中以 "Authorization: Bearer {token}" 的形式传递
     */
    @GetMapping("/validate")
    @Operation(summary = "验证Token", description = "验证请求头中的token并返回用户ID")
    public Result<String> validateTokenAndGetUserId(HttpServletRequest request) {
        String userId = tokenService.validateTokenAndGetUserId(request);
        return Result.success(userId);
    }
}