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

package shop

import (
	"context"
	"errors"
	"time"

	"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"

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

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

// 拒绝邀请
func NewRejectInvitationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RejectInvitationLogic {
	return &RejectInvitationLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RejectInvitationLogic) RejectInvitation(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, contextj.ERRILLEGALUSER
		}
		return nil, err
	}
	player := playerResp.GetPlayers()
	if player == nil {
		return nil, contextj.ERRILLEGALUSER
	}

	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, contextj.ERRILLEGALUSER
	}

	_, err = l.svcCtx.ShopRpc.UpdateShopInvitations(l.ctx, &pb.UpdateShopInvitationsReq{
		Id:          req.Id,
		ShopId:      invitation.ShopInvitations.ShopId,
		PlayerId:    invitation.ShopInvitations.PlayerId,
		Status:      "rejected",
		InvitedBy:   invitation.ShopInvitations.InvitedBy,
		CreatedAt:   invitation.ShopInvitations.CreatedAt,
		RespondedAt: time.Now().Unix(),
	})
	if err != nil {
		return nil, err
	}

	return &types.EmptyResp{}, nil
}
