package cn.reghao.tnb.auth.app.controller;

import cn.reghao.tnb.common.web.WebResult;
import cn.reghao.jutil.jdk.serializer.JsonConverter;
import cn.reghao.tnb.auth.app.model.vo.AccountToken;
import cn.reghao.tnb.auth.app.service.AccountTokenService;
import com.google.gson.JsonObject;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @author reghao
 * @date 2023-10-19 14:38:03
 */
@Tag(name = "帐号认证页面")
@Controller
public class AccountAuthController {
    private final AccountTokenService accountTokenService;

    public AccountAuthController(AccountTokenService accountTokenService) {
        this.accountTokenService = accountTokenService;
    }

    @Operation(summary = "帐号首页", description = "N")
    @GetMapping("/")
    public String indexPage() {
        return "/index";
    }

    @Operation(summary = "帐号认证页面", description = "N")
    @GetMapping("/login")
    public String loginPage() {
        return "/auth/login";
    }

    @Operation(summary = "帐号登出接口", description = "N")
    @GetMapping("/logout")
    public String logoutPage() {
        // 注销当前登入的设备
        accountTokenService.logout();
        return "redirect:/login";
    }

    @Operation(summary = "刷新 jwt 令牌", description = "N")
    @PostMapping(value = "/api/auth/token/refresh", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String refreshToken(@RequestBody String refreshToken) throws Exception {
        JsonObject jsonObject = JsonConverter.jsonToJsonElement(refreshToken).getAsJsonObject();
        String refreshToken1 = jsonObject.get("refreshToken").getAsString();
        AccountToken accountToken = accountTokenService.getUserToken(refreshToken1);
        return WebResult.success(accountToken);
    }
}
