package login

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/pingcap/log"
	"go.uber.org/zap"

	"github.com/pingcap-inc/clinic/pkg/api/error"
	"github.com/pingcap-inc/clinic/pkg/auth/oauth"
)

// TODO: it shoud be removed after we complete the job
func (s *LoginService) Test(c *gin.Context) {
	sess, err := oauth.Authers[oauth.ASKTUG].Exchange(c.Request.Context(), c.Query("state"), c.Query("code"))
	if err != nil {
		_ = c.Error(error.ErrNotFound.New("not found the user"))
		log.Error("get user failed", zap.Error(err))
		return
	}

	if sess == nil {
		_ = c.Error(error.ErrNotFound.New("not found the user"))
		return
	}

	key, err := s.Session.NewSession(sess)
	if err != nil {
		log.Error("new session failed", zap.Error(err))
		return
	}

	s.Session.SetCookie(c, key)

	c.JSON(http.StatusOK, ValidationResp{
		SessionKey: key,
	})
}
