package com.srs.web.controller.common;

import com.srs.common.annotation.Anonymous;
import com.srs.common.core.controller.BaseController;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.core.domain.model.LoginUser;
import com.srs.common.utils.HttpJsonUtil;
import com.srs.common.utils.JwtUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/coze")
public class CozeController extends BaseController {

    @GetMapping("/get-access-token")
    public Map<String, Object> getAccessToken() {
        Map<String, Object> resp = new HashMap<>();
        try {
            //获取当前登录用户信息
            LoginUser loginUser = getLoginUser();
            SysUser user = loginUser.getUser();

            // 1. 生成 JWT
            String jwt = JwtUtil.generateJwt(user.getUserName());

            // 2. 拼装请求 Coze
            Map<String, Object> body = new HashMap<>();
            body.put("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
            body.put("duration_seconds", 600);

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Authorization", "Bearer " + jwt);

            String cozeResult = HttpJsonUtil.postJson("https://api.coze.cn/api/permission/oauth2/token", body, headers);
            resp.put("code", 200);
            resp.put("data", cozeResult);
            return resp;
        } catch (Exception e) {
            resp.put("code", 500);
            resp.put("msg", "获取 token 失败: " + e.getMessage());
            return resp;
        }
    }
}
