package auth

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/api/internal/svc"
	"git.noahlan.cn/n-admin/n-admin-server/api/internal/types"
	"git.noahlan.cn/n-admin/n-admin-server/dal/errx"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/types/core"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus"

	"net/http"
)

type OauthLoginByPhoneLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewOauthLoginByPhoneLogic(r *http.Request, ctx context.Context, svcCtx *svc.ServiceContext) *OauthLoginByPhoneLogic {
	return &OauthLoginByPhoneLogic{
		r:      r,
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OauthLoginByPhoneLogic) OauthLoginByPhone(req *types.OauthLoginByPhoneCodeReq) (resp *types.LoginResp, err error) {
	var phoneNumber string
	rpcProvider, err := l.svcCtx.CoreRpc.GetOauthProvider(l.ctx, &core.OauthProviderReq{
		Name: req.Provider,
	})
	if err != nil {
		return nil, err
	}
	if !rpcProvider.Init {
		return nil, nstatus.NewBizErrWithCode(errx.ProviderNotInit)
	}
	// TODO Social Helper
	user, err := l.svcCtx.CoreRpc.GetUser(l.ctx, &core.UserReq{
		PhoneNumber: phoneNumber,
	})
	// 登录
	resp, err = login(l.ctx, l.svcCtx, l.r, user)
	if err != nil {
		return nil, err
	}
	return
}
