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 ApplyFetch(ctx context.Context, in *pb.VersionRequest) (reply *pb.ApplyFetchReply, err error) {
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	var cacheErr error
	if in.Version == 0 {
		reply, err = common.CollectionFriendApply(auth.ID)
		if err == nil {
			cacheErr = common.SetCache(auth.Identity, "apply", reply)
		}

	}

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

	if in.Version != cache.Version {
		reply, err = common.CollectionFriendApply(auth.ID)
		if err == nil {
			cacheErr = common.SetCache(auth.Identity, "apply", 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
}
