package jd

import (
	"encoding/json"
	"errors"
	"os"
)

func ClientAuth() (*ClientAuthResp, error) {
	var username = os.Getenv("JD_USERNAME")
	if username == "" {
		return nil, errors.New("JD_USERNAME 环境变量未设置")
	}

	var password = os.Getenv("JD_PASSWORD")
	if password == "" {
		return nil, errors.New("JD_PASSWORD 环境变量未设置")
	}

	path := "/client/auth"
	resp, err := Post(path, map[string]any{
		"username": username,
		"password": password,
	}, false)
	if err != nil {
		return nil, err
	}

	var respData = new(ClientAuthResp)
	if err := json.NewDecoder(resp).Decode(respData); err != nil {
		panic("响应解析失败: " + err.Error())
	}

	if respData.Code != 0 {
		panic("响应失败: " + respData.Meta)
	}

	return respData, nil
}

type ClientAuthResp struct {
	Code int    `json:"code"`
	Meta string `json:"meta"`
	Data string
}
