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/service"
)

// 获取隐私数据列表
func ListPrivateData(ctx context.Context, in *pb.FetchRequest) (reply *pb.ListPrivateDataResponse, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request page_no,page_size.
	if in.GetPageNo() < 1 {
		in.PageNo = 1
	}
	if in.GetPageSize() < 10 {
		in.PageSize = 50
	}

	// logic code
	var privateDataList []models.CloudPrivate
	var total int64

	// 获取总数
	if err := impl.DBService.Model(&models.CloudPrivate{}).Where("passport_id = ?", auth.ID).Count(&total).Error; err != nil {
		return nil, err
	}

	// 分页查询
	offset := (in.PageNo - 1) * in.PageSize
	if err := impl.DBService.Where("passport_id = ?", auth.ID).
		Order("created_at DESC").
		Offset(int(offset)).
		Limit(int(in.PageSize)).
		Find(&privateDataList).Error; err != nil {
		return nil, err
	}

	// 转换数据
	var dataItems []*pb.CloudPrivateItem
	for _, data := range privateDataList {
		dataItems = append(dataItems, &pb.CloudPrivateItem{
			Id:          uint64(data.ID),
			Identity:    data.Identity,
			DataType:    data.DataType,
			Title:       data.Title,
			Description: data.Description,
			Data:        data.Data,
			IsEncrypted: data.IsEncrypted,
			Tags:        data.Tags,
			CreatedAt:   data.CreatedAt.Format(time.RFC3339),
			UpdatedAt:   data.UpdatedAt.Format(time.RFC3339),
		})
	}

	reply = &pb.ListPrivateDataResponse{
		Data:  dataItems,
		Total: total,
	}

	return reply, nil
}
