package fastgpt

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"net/http"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
)

type SetTokenLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	rw     http.ResponseWriter
}

func NewSetTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext, rw http.ResponseWriter) *SetTokenLogic {
	return &SetTokenLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		rw:     rw,
	}
}

func (l *SetTokenLogic) SetToken(username string) (resp *types.BaseMsgResp, err error) {
	claims, err := ParseJWT(username, l.svcCtx.Config.Auth.AccessSecret)
	if err != nil {
		return nil, fmt.Errorf("invalid token")
	}
	data, err := l.svcCtx.CoreRpc.GetUserById(context.TODO(), &core.UUIDReq{Id: claims.UserId})
	token, err := l.getToken(strconv.FormatUint(*data.DepartmentId, 10))
	if err != nil {
		return nil, fmt.Errorf("invalid token")
	}
	//if err != nil {
	//	return nil, err
	//}
	// 创建一个新的 Cookie
	cookie := &http.Cookie{
		Name:     "fastgpt_token",
		Value:    token, // 假设 req.Token 是你要设置的 Cookie 值
		Domain:   ".gkscrm.com",
		SameSite: http.SameSiteNoneMode,
		Secure:   true, // 如果 SameSite 设置为 None，必须设置 Secure 为 true
		HttpOnly: false,
		Path:     "/",
	}

	// 设置 Cookie 到响应中
	http.SetCookie(l.rw, cookie)

	// 返回响应消息
	resp = &types.BaseMsgResp{
		Code: 0,
		Msg:  "Cookie set successfully",
	}

	return
}

func (l *SetTokenLogic) getToken(username string) (string, error) {
	// 设置请求的 URL 和请求体
	url := "https://agent.gkscrm.com/api/support/user/account/loginByPassword"
	payload := map[string]string{
		"username": username,
		"password": "578fd6dfa3f71a8fadf5dc60d0e7115881db4c36504f83c4a0f4422107162c36",
	}

	// 将请求体编码为 JSON
	jsonPayload, err := json.Marshal(payload)
	if err != nil {
		return "", err
	}

	// 创建 HTTP 请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload))
	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("failed to login, status code: %d", resp.StatusCode)
	}

	// 解析响应体
	var response map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&response)
	if err != nil {
		return "", err
	}

	// 提取 token
	data, ok := response["data"].(map[string]interface{})
	if !ok {
		return "", fmt.Errorf("invalid response format")
	}
	token, ok := data["token"].(string)
	if !ok {
		return "", fmt.Errorf("token not found in response")
	}

	return token, nil
}

type Claims struct {
	RoleId string `json:"roleId"`
	UserId string `json:"userId"`
	jwt.RegisteredClaims
}

func ParseJWT(tokenString, accessSecret string) (*Claims, error) {
	claims := &Claims{}

	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(accessSecret), nil
	})

	if err != nil {
		return nil, fmt.Errorf("invalid token")
	}

	if !token.Valid {
		return nil, fmt.Errorf("invalid token")
	}

	return claims, nil
}
