// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2

package user

import (
	"context"
	"errors"
	"strconv"

	"juwan-backend/app/users/rpc/usercenter"
	"juwan-backend/common/utils/contextj"

	"juwan-backend/app/users/api/internal/svc"
	"juwan-backend/app/users/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type FollowUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 关注用户
func NewFollowUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FollowUserLogic {
	return &FollowUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FollowUserLogic) FollowUser(req *types.FollowUserReq) (resp *types.EmptyResp, err error) {
	userId, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, errors.New("unauthorized")
	}

	followeeId, err := strconv.ParseInt(req.Id, 10, 64)
	if err != nil {
		return nil, errors.New("invalid user id")
	}

	_, err = l.svcCtx.UserRpc.AddUserFollows(l.ctx, &usercenter.AddUserFollowsReq{
		FollowerId: userId,
		FolloweeId: followeeId,
		CreatedAt:  0,
	})
	if err != nil {
		logx.Errorf("add user follow err: %v", err)
		return nil, errors.New("failed to follow user")
	}
	return &types.EmptyResp{}, nil
}
