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

package shop

import (
	"context"
	"errors"
	"juwan-backend/app/player/rpc/playerservice"
	"juwan-backend/app/shop/api/internal/svc"
	"juwan-backend/app/shop/api/internal/types"
	"juwan-backend/app/shop/rpc/pb"
	"juwan-backend/common/utils/contextj"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

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

// 接受邀请
func NewAcceptInvitationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AcceptInvitationLogic {
	return &AcceptInvitationLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AcceptInvitationLogic) AcceptInvitation(req *types.AcceptInvitationReq) (resp *types.EmptyResp, err error) {
	userId, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	playerResp, err := l.svcCtx.PlayerRpc.GetPlayerByUserId(l.ctx, &playerservice.SearchPlayersReq{UserId: &userId})
	if err != nil {
		st, _ := status.FromError(err)
		if st.Code() == codes.NotFound {
			return nil, errors.New("bad request: invitation not found or not owned by user")
		}
		return nil, err
	}
	player := playerResp.GetPlayers()
	if player == nil {
		return nil, errors.New("bad request: invitation not found or not owned by user")
	}
	invitation, err := l.svcCtx.ShopRpc.GetShopInvitationsById(l.ctx, &pb.GetShopInvitationsByIdReq{Id: req.Id})
	if err != nil {
		return nil, err
	}
	if invitation.ShopInvitations == nil {
		return nil, errors.New("invitation not found")
	}
	if invitation.ShopInvitations.PlayerId != player.Id {
		return nil, errors.New("bad request: invitation not found or not owned by user")
	}

	i, err := l.svcCtx.ShopRpc.UpdateShopInvitations(l.ctx, &pb.UpdateShopInvitationsReq{
		Id:          req.Id,
		ShopId:      invitation.ShopInvitations.ShopId,
		PlayerId:    player.Id,
		Status:      "accepted",
		InvitedBy:   invitation.ShopInvitations.InvitedBy,
		CreatedAt:   invitation.ShopInvitations.CreatedAt,
		RespondedAt: time.Now().Unix(),
	})
	if err != nil {
		return nil, err
	}
	_, err = l.svcCtx.ShopRpc.AddShopPlayers(l.ctx, &pb.AddShopPlayersReq{
		ShopId:    i.ShopInvitations.ShopId,
		PlayerId:  player.Id,
		IsPrimary: false,
		JoinedAt:  time.Now().Unix(),
		LeftAt:    0,
	})
	if err != nil {
		return nil, err
	}

	_ = i
	return &types.EmptyResp{}, nil
}
