// Package apiserver contains functionality that is common to all services.
package apiserver

import (
	"github.com/gin-gonic/gin"
	"github.com/microcosm-cc/bluemonday"
	"github.com/tidbcloud/internal-portal/core-portal/auth"
)

// APIOperationsServiceState contains the service state
type APIOperationsServiceState struct {
	sanitizerPolicy *bluemonday.Policy
}

// OperationsService is the common interface for our services
type APIOperationsService interface {
	CurrentUser(*gin.Context) *auth.User
	SanitizerPolicy() *bluemonday.Policy
}

// New constructs an OperationsService
func New() *APIOperationsServiceState {
	return &APIOperationsServiceState{
		sanitizerPolicy: bluemonday.UGCPolicy(),
	}
}

func (s *APIOperationsServiceState) SanitizerPolicy() *bluemonday.Policy {
	return s.sanitizerPolicy
}

// CurrentUser gets the user from the request.
// This function panics if there is no user in the db for the email or no email claim in the context.
func (s *APIOperationsServiceState) CurrentUser(c *gin.Context) *auth.User {
	u, err := GetUserFromContext(c)
	if err != nil {
		panic("expected user claim")
	}
	return u
}
