package utils

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"errors"
	"io"
)

type DeviceValidateResponse struct {
	Status      string `json:"status"`       // 设备状态
	LicenseType string `json:"license_type"` // 授权类型
	ExpireTime  string `json:"expire_time"`  // 过期时间
	StartCount  int    `json:"start_count"`  // 启动次数
	MaxUses     int    `json:"max_uses"`     // 最大使用次数
	Timestamp   int64  `json:"timestamp"`    // 时间戳
	Signature   string `json:"signature"`    // 签名
}

// EncryptResponse 加密设备验证响应
func EncryptResponse(data DeviceValidateResponse, key []byte) (string, error) {
	// 序列化数据
	plaintext, err := json.Marshal(data)
	if err != nil {
		return "", err
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}

	// 创建随机IV
	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return "", err
	}

	// 加密
	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

	// 返回base64编码的密文
	return base64.StdEncoding.EncodeToString(ciphertext), nil
}

// DecryptResponse 解密设备验证响应
func DecryptResponse(encrypted string, key []byte) (*DeviceValidateResponse, error) {
	ciphertext, err := base64.StdEncoding.DecodeString(encrypted)
	if err != nil {
		return nil, err
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	if len(ciphertext) < aes.BlockSize {
		return nil, errors.New("密文太短")
	}

	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]

	stream := cipher.NewCFBDecrypter(block, iv)
	stream.XORKeyStream(ciphertext, ciphertext)

	var response DeviceValidateResponse
	if err := json.Unmarshal(ciphertext, &response); err != nil {
		return nil, err
	}

	return &response, nil
}
