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

// 按类型获取隐私数据
func GetPrivateDataByType(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
	}

	// validate data type
	dataType, exists := in.Params["data_type"]
	if !exists || strings.TrimSpace(dataType) == "" {
		return nil, errcode.ErrInvalidArgument
	}

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

	// 构建查询
	query := impl.DBService.Model(&models.CloudPrivate{}).Where("passport_id = ? AND data_type = ?", auth.ID, dataType)

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 分页查询
	offset := (in.PageNo - 1) * in.PageSize
	if err := query.
		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
}
