package logic

import (
	"context"
	"errors"
	"juwan-backend/app/shop/rpc/internal/models/shopplayers"
	"time"

	"juwan-backend/app/shop/rpc/internal/svc"
	"juwan-backend/app/shop/rpc/pb"

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

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

func NewUpdateShopPlayersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateShopPlayersLogic {
	return &UpdateShopPlayersLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateShopPlayersLogic) UpdateShopPlayers(in *pb.UpdateShopPlayersReq) (*pb.UpdateShopPlayersResp, error) {
	if in.ShopId <= 0 || in.PlayerId <= 0 {
		return nil, errors.New("invalid shop_id or player_id")
	}

	updater := l.svcCtx.ShopModelRW.ShopPlayers.Update().
		Where(
			shopplayers.ShopIDEQ(in.ShopId),
			shopplayers.PlayerIDEQ(in.PlayerId),
		).
		SetIsPrimary(in.IsPrimary)

	if in.LeftAt > 0 {
		t := time.Unix(in.LeftAt, 0)
		updater = updater.SetLeftAt(t)
	}

	affected, err := updater.Save(l.ctx)
	if err != nil {
		logx.Errorf("update shop players failed, %s", err.Error())
		return nil, errors.New("update shop players failed")
	}
	if affected == 0 {
		return nil, errors.New("shop player not found")
	}

	return &pb.UpdateShopPlayersResp{}, nil
}
