package account

import (
	"context"

	"bsm/full/module/base/passport/internal/impl"
	"bsm/full/module/base/passport/internal/models"
	pb "bsm/full/module/base/passport/pb"
	"git.apinb.com/bsm-sdk/core/service"
)

// 获取会员的相关统计数据
func Statistics(ctx context.Context, in *pb.StatisticsRequest) (reply *pb.StatisticsReply, err error) {
	// parse authorization meta.
	AUTH, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// Validate request fields
	if len(in.Field) == 0 {
		return &pb.StatisticsReply{
			Data: make(map[string]int64),
		}, nil
	}

	// Initialize result map
	result := make(map[string]int64)

	// Get statistics based on requested fields
	for _, field := range in.Field {
		switch field {
		case "login_count":
			// Count login records for this user
			var count int64
			impl.DBService.Model(&models.PassportAccount{}).
				Where("id = ?", AUTH.ID).
				Count(&count)
			result[field] = count
		case "tag_count":
			// Count tags for this user
			var count int64
			impl.DBService.Model(&models.PassportTags{}).
				Where("passport_id = ?", AUTH.ID).
				Count(&count)
			result[field] = count
		default:
			// Unknown field, set to 0
			result[field] = 0
		}
	}

	return &pb.StatisticsReply{
		Data: result,
	}, nil
}
