package debugportal

import (
	"strings"

	"github.com/pingcap/dbaas/central/config"
	debugmodel "github.com/pingcap/dbaas/central/model/debug"
	topsqlmodel "github.com/pingcap/dbaas/central/model/debug/topsql"
	"github.com/pingcap/dbaas/central/service"
	"github.com/pingcap/dbaas/pkg/auth/debug"
	"github.com/tidbcloud/idl/pbgen/proto/central"
	"golang.org/x/oauth2"
)

type debugPortalService struct {
	central.UnimplementedCentralDebugPortalServiceServer
	service.OperationsService
	model          debugmodel.Model
	topsqlModel    topsqlmodel.TopSQLModel
	config         *config.DebugPortalConfig
	oAuthClient    *debug.OAuthClient
	sessionManager *debug.SessionManager
}

var _ central.CentralDebugPortalServiceServer = (*debugPortalService)(nil)

func NewService(
	s service.OperationsService,
	model debugmodel.Model,
	topsqlModel topsqlmodel.TopSQLModel,
	debugPortalConfig *config.DebugPortalConfig,
	debugSessionManager *debug.SessionManager,
) central.CentralDebugPortalServiceServer {
	oauthConfig := oauth2.Config{
		ClientID:     debugPortalConfig.OAuthClientID,
		ClientSecret: debugPortalConfig.OAuthClientSecret,
		Scopes:       strings.Split(debugPortalConfig.OAuthScopes, " "),
		Endpoint: oauth2.Endpoint{
			AuthURL:  debugPortalConfig.OAuthAuthorizationURL,
			TokenURL: debugPortalConfig.OAuthTokenURL,
		},
	}
	return &debugPortalService{
		OperationsService: s,
		model:             model,
		topsqlModel:       topsqlModel,
		config:            debugPortalConfig,
		oAuthClient:       debug.NewOAuthClient(oauthConfig, debugPortalConfig.OAuthUserInfoURL),
		sessionManager:    debugSessionManager,
	}
}
