package private

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

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

// 加密数据
func EncryptData(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
	// 简单的AES加密实现
	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
	}

	// 生成随机nonce
	nonce := make([]byte, gcm.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		return nil, errcode.ErrInternal
	}

	// 加密数据
	ciphertext := gcm.Seal(nonce, nonce, []byte(in.Data), nil)

	// 返回base64编码的加密数据
	encryptedData := base64.StdEncoding.EncodeToString(ciphertext)

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