package jd

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/redis/go-redis/v9"
	"io"
	"net/http"
	"time"
	"zzman/clients"
)

const base = "https://smart.jdbox.xyz:58001"

func Post(path string, data any, auth ...bool) (io.ReadCloser, error) {

	reqBytes, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", base+path, bytes.NewReader(reqBytes))
	if err != nil {
		return nil, err
	}
	defer req.Body.Close()

	req.Header.Set("Content-Type", "application/json")

	if len(auth) == 0 || auth[0] {
		token, err := Token()
		if err != nil {
			return nil, fmt.Errorf("获取令牌失败: %w", err)
		}
		req.Header.Set("X-Token", token)
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("%s 响应失败: %s", path, resp.Status)
	}

	return resp.Body, nil
}

func Token() (string, error) {

	// 尝试从 Redis 获取缓存的 token
	token, err := clients.Redis.Get(context.Background(), "token").Result()
	if err != nil && !errors.Is(err, redis.Nil) {
		return "", fmt.Errorf("获取 token 失败: %w", err)
	}
	if token != "" {
		return token, nil
	}

	// 如果缓存中没有 token，则进行认证请求
	resp, err := ClientAuth()
	if err != nil {
		return "", fmt.Errorf("认证请求失败: %w", err)
	}

	// 返回请求的 token
	token = resp.Data
	if err := clients.Redis.Set(context.Background(), "token", token, 6*24*time.Hour).Err(); err != nil {
		return "", fmt.Errorf("缓存 token 失败: %w", err)
	}

	return token, nil
}
