package sso

import (
	"net/http"
	"time"

	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"
	"gorm.io/gorm"

	"gitlab.com/mbugroup/lti-api.git/internal/cache"
	"gitlab.com/mbugroup/lti-api.git/internal/config"
	"gitlab.com/mbugroup/lti-api.git/internal/middleware"
	ssoController "gitlab.com/mbugroup/lti-api.git/internal/modules/sso/controllers"
	"gitlab.com/mbugroup/lti-api.git/internal/modules/sso/session"
	userRepository "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
)

func Routes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
	ttl := config.SSOPKCETTL
	if ttl <= 0 {
		ttl = 5 * time.Minute
	}

	store := session.NewStore(cache.MustRedis(), ttl)
	ctrl := ssoController.NewController(&http.Client{Timeout: 10 * time.Second}, store, session.GetRevocationStore())
	userRepo := userRepository.NewUserRepository(db)
	syncCtrl := ssoController.NewUserSyncController(validate, userRepo, cache.Redis(), config.SSOClients)
	masterCtrl := ssoController.NewMasterDataController(db, cache.Redis(), config.SSOClients)

	group := router.Group("/sso")
	group.Get("/start", middleware.NewLimiter(30, time.Minute), ctrl.Start)
	group.Get("/callback", ctrl.Callback)
	group.Get("/userinfo", middleware.NewLimiter(60, time.Minute), ctrl.UserInfo)
	group.Post("/refresh", middleware.NewLimiter(60, time.Minute), ctrl.Refresh)
	group.Post("/logout", middleware.NewLimiter(60, time.Minute), ctrl.Logout)
	group.Post("/users/sync", middleware.NewLimiter(30, time.Minute), syncCtrl.Sync)
	group.Get("/master/areas", middleware.NewLimiter(60, time.Minute), masterCtrl.GetAreas)
	group.Get("/master/locations", middleware.NewLimiter(60, time.Minute), masterCtrl.GetLocations)
}
