package private

import (
	"context"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"strings"
	"time"

	pb "bsm/full/module/base/cloud/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/service"
)

// 解密数据
func DecryptData(ctx context.Context, in *pb.DataRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	_, err = service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request
	if strings.TrimSpace(in.Data) == "" {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.Key) == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	// 解码base64数据
	ciphertext, err := base64.StdEncoding.DecodeString(in.Data)
	if err != nil {
		return nil, errcode.ErrInvalidArgument
	}

	key := []byte(in.Key)
	if len(key) != 32 {
		// 如果密钥长度不是32字节，进行填充或截断
		if len(key) < 32 {
			for len(key) < 32 {
				key = append(key, 0)
			}
		} else {
			key = key[:32]
		}
	}

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

	// 使用GCM模式进行解密
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, errcode.ErrInternal
	}

	// 检查数据长度
	if len(ciphertext) < gcm.NonceSize() {
		return nil, errcode.ErrInvalidArgument
	}

	// 分离nonce和密文
	nonce := ciphertext[:gcm.NonceSize()]
	ciphertext = ciphertext[gcm.NonceSize():]

	// 解密数据
	plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
	if err != nil {
		return nil, errcode.ErrInvalidArgument
	}

	return &pb.StatusReply{
		Details: string(plaintext),
		Timeseq: time.Now().UnixMilli(),
	}, nil
}
