package com.guwan.controller.login;

import com.guwan.service.TokenService;
import com.guwan.util.IPUtils;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private TokenService tokenService;

    @GetMapping("/login")
    @PermitAll
    @Operation(summary = "使用账号密码登录")
    public String login(String userId, HttpServletRequest request) {
        String ip = IPUtils.getIpAddr(request);
        System.out.println("ip = " + ip);
       return tokenService.createToken(userId, ip);

    }

    @GetMapping("/getInfo")
    @PermitAll
    @Operation(summary = "查询用户信息")
    public String getInfo(String token) {


        if (!tokenService.checkToken(token)) {
            return "token无效";
        }

        try {
            tokenService.getInfo(token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            tokenService.validateAndExtendToken(token);
        }
        return "getInfo";
    }
}
