package logic

import (
	"context"
	"encoding/json"
	"errors"
	"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"
)

var USER_TOKEN_TEMP = "jwt:%v"

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

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

func (l *ValidateTokenLogic) ValidateToken(in *pb.ValidateTokenReq) (*pb.ValidateTokenResp, error) {

	payload, err := l.svcCtx.JwtManager.Valid(l.ctx, in.Token)
	if err != nil {
		return nil, err
	}
	if payload == nil || payload.UserId != in.UserId {
		return nil, errors.New("token user mismatch")
	}
	//users, err := l.svcCtx.UsersModelRO.FindOne(l.ctx, in.UserId)
	user, err := l.svcCtx.UsersModelRO.Users.Query().
		Where(users.IDEQ(payload.UserId)).
		Select(users.FieldCurrentRole).
		First(l.ctx)
	if err != nil {
		return nil, err
	}

	userJson, err := json.Marshal(user.CurrentRole)
	if err != nil {
		logx.Errorf("json marshal err: %v", err)
		return nil, errors.New("internal error")
	}

	return &pb.ValidateTokenResp{
		Valid:    true,
		Message:  "OK",
		UserId:   payload.UserId,
		RoleType: string(userJson),
	}, nil
}
