package private

import (
	"context"
	"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"
)

// 获取隐私数据详情
func GetPrivateData(ctx context.Context, in *pb.IdentRequest) (reply *pb.CloudPrivateItem, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request id,identity.
	if in.Id == 0 && in.Identity == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	var privateData models.CloudPrivate
	query := impl.DBService.Where("passport_id = ?", auth.ID)

	if in.Id > 0 {
		query = query.Where("id = ?", in.Id)
	} else {
		query = query.Where("identity = ?", in.Identity)
	}

	if err := query.First(&privateData).Error; err != nil {
		printer.Error("Private data not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	reply = &pb.CloudPrivateItem{
		Id:          uint64(privateData.ID),
		Identity:    privateData.Identity,
		DataType:    privateData.DataType,
		Title:       privateData.Title,
		Description: privateData.Description,
		Data:        privateData.Data,
		IsEncrypted: privateData.IsEncrypted,
		Tags:        privateData.Tags,
		CreatedAt:   privateData.CreatedAt.Format(time.RFC3339),
		UpdatedAt:   privateData.UpdatedAt.Format(time.RFC3339),
	}

	return reply, nil
}
