package private

import (
	"context"
	"strings"
	"time"

	"bsm/full/module/base/cloud/internal/impl"
	"bsm/full/module/base/cloud/internal/models"
	pb "bsm/full/module/base/cloud/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"git.apinb.com/bsm-sdk/core/types"
	"git.apinb.com/bsm-sdk/core/utils"
)

// 创建隐私数据
func CreatePrivateData(ctx context.Context, in *pb.CreatePrivateDataRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// valid code
	if strings.TrimSpace(in.DataType) == "" {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.Title) == "" {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.CloudIdentity) == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	record := models.CloudPrivate{
		Std_IICUDS: types.Std_IICUDS{
			Identity: utils.UUID(),
		},
		Std_Passport: types.Std_Passport{
			PassportID:       auth.ID,
			PassportIdentity: auth.Identity,
		},
		CloudBase: models.CloudBase{
			CloudID:       uint(in.CloudId),
			CloudIdentity: in.CloudIdentity,
		},
		DataType:    in.DataType,
		Title:       in.Title,
		Description: in.Description,
		Data:        in.Data,
		IsEncrypted: in.IsEncrypted,
		Tags:        in.Tags,
	}

	if err := impl.DBService.Create(&record).Error; err != nil {
		printer.Error("Create private data error: %v", err)
		return nil, errcode.ErrDB
	}

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