package logic

import (
	"context"
	"errors"
	"slices"

	"juwan-backend/app/users/rpc/internal/models/users"
	"juwan-backend/app/users/rpc/internal/svc"
	"juwan-backend/app/users/rpc/pb"

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

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

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

var userRoles = []string{"consumer", "owner", "player", "admin"}

func (l *SwitchRoleLogic) SwitchRole(in *pb.SwitchRoleReq) (*pb.SwitchRoleResp, error) {
	user, err := l.svcCtx.UsersModelRO.Users.Query().
		Select(users.FieldVerifiedRoles).
		Where(users.IDEQ(in.UserId)).
		First(l.ctx)
	if err != nil {
		logx.Errorf("find user error by switch role, err: %v", err.Error())
		return &pb.SwitchRoleResp{
			Success: false,
		}, errors.New("failed to find user")
	}

	if !slices.Contains(userRoles, in.NewRole) {
		logx.Infof("user role not found by userId: %v", in.UserId)
		return nil, errors.New("user role not found by userId")
	}

	if !slices.Contains(user.VerifiedRoles.Elements, in.NewRole) {
		logx.Infof("user verified role not exists, user: %v", in.UserId)
		return nil, errors.New("no permission to operate")
	}

	user, err = l.svcCtx.UsersModelRW.Users.UpdateOneID(in.UserId).
		SetCurrentRole(in.NewRole).
		Save(l.ctx)
	if err != nil {
		logx.Errorf("failed to update user role, userId: %v, err: %v", in.UserId, err.Error())
		return nil, errors.New("failed to update user")
	}

	return &pb.SwitchRoleResp{
		Success: true,
	}, nil
}
