package friend

import (
	"context"

	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"bsm/full/module/social/relation/internal/logic/common"
	pb "bsm/full/module/social/relation/pb"
)

// 获取好友列表
func Fetch(ctx context.Context, in *pb.VersionRequest) (reply *pb.FriendsReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	var cacheErr error
	if in.Version == 0 {
		reply, err = common.CollectionFriendData(auth.ID)
		if err == nil {
			cacheErr = common.SetCache(auth.Identity, "friends", reply)
		}

	}

	cache, err := common.GetCache(auth.Identity, "friends")
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrRedis
	}

	if in.Version != cache.Version {
		reply, err = common.CollectionFriendData(auth.ID)
		if err == nil {
			cacheErr = common.SetCache(auth.Identity, "friends", reply)
		}
	}

	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	if cacheErr != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrRedis
	}
	return reply, nil
}
