package router

import (
	"strings"

	"git.ex.umbach.dev/LMS/libcore/models"
	"github.com/gofiber/fiber/v2"
	"lms.de/backend/modules/config"
	"lms.de/backend/modules/database"
	"lms.de/backend/modules/utils"
	myapp "lms.de/backend/routers/router/api/v1/app"
	"lms.de/backend/routers/router/api/v1/lessons"
	"lms.de/backend/routers/router/api/v1/organization"
	"lms.de/backend/routers/router/api/v1/user"
)

func SetupRoutes(app *fiber.App) {
	v1 := app.Group("/v1")

	v1.Get("/app", handleOrganizationSubdomain, requestAccessValidation, myapp.GetApp)

	o := v1.Group("/organization")
	o.Post("/", organization.CreateOrganization)
	o.Get("/team/members", handleOrganizationSubdomain, requestAccessValidation, organization.GetTeamMembers)
	o.Post("/team/members", handleOrganizationSubdomain, requestAccessValidation, organization.CreateTeamMember)
	o.Get("/settings", handleOrganizationSubdomain, requestAccessValidation, organization.GetOrganizationSettings)
	o.Patch("/settings", handleOrganizationSubdomain, requestAccessValidation, organization.UpdateOrganizationSettings)
	o.Post("/file/:type", handleOrganizationSubdomain, requestAccessValidation, organization.UpdateOrganizationFile)
	o.Get("/subdomain/:subdomain", organization.IsSubdomainAvailable)
	o.Patch("/subdomain/:subdomain", handleOrganizationSubdomain, requestAccessValidation, organization.UpdateSubdomain)
	o.Get("/roles", handleOrganizationSubdomain, requestAccessValidation, organization.GetRoles)
	// o.Post("/roles", handleOrganizationSubdomain, requestAccessValidation, organization.CreateRole)

	u := v1.Group("/user")
	u.Post("/auth/login", handleOrganizationSubdomain, user.UserLogin)

	l := v1.Group("/lessons")
	l.Get("/", handleOrganizationSubdomain, requestAccessValidation, lessons.GetLessons)
	l.Post("/", handleOrganizationSubdomain, requestAccessValidation, lessons.CreateLesson)
	l.Get("/:lessonId/contents", handleOrganizationSubdomain, requestAccessValidation, lessons.GetLessonContents)
	l.Get("/:lessonId/settings", handleOrganizationSubdomain, requestAccessValidation, lessons.GetLessonSettings)
	l.Patch("/:lessonId/preview/title", handleOrganizationSubdomain, requestAccessValidation, lessons.UpdateLessonPreviewTitle)
	l.Post("/:lessonId/preview/thumbnail", handleOrganizationSubdomain, requestAccessValidation, lessons.UpdateLessonPreviewThumbnail)
	l.Patch("/:lessonId/state", handleOrganizationSubdomain, requestAccessValidation, lessons.UpdateLessonState)
	l.Post("/:lessonId/contents", handleOrganizationSubdomain, requestAccessValidation, lessons.AddLessonContent)
	l.Patch("/:lessonId/contents/:contentId", handleOrganizationSubdomain, requestAccessValidation, lessons.UpdateLessonContent)
	l.Patch("/:lessonId/contents/:contentId/position", handleOrganizationSubdomain, requestAccessValidation, lessons.UpdateLessonContentPosition)
	l.Delete("/:lessonId/contents/:contentId", handleOrganizationSubdomain, requestAccessValidation, lessons.DeleteLessonContent)
	l.Post("/:lessonId/contents/:contentId/file/:type", handleOrganizationSubdomain, requestAccessValidation, lessons.UploadLessonContentFile)

	app.Static("/static", config.Cfg.FolderPaths.PublicStatic)
}

func userSessionValidation(c *fiber.Ctx) error {
	xAuthorization := utils.GetXAuhorizationHeader(c)

	if len(xAuthorization) != utils.LenHeaderXAuthorization {
		return fiber.ErrUnauthorized
	}

	var userSession models.UserSession

	database.DB.Select("session", "user_id").First(&userSession, "session = ? AND organization_id = ?", xAuthorization, c.Locals("organizationId"))

	if userSession.Session != xAuthorization {
		return fiber.ErrUnauthorized
	}

	c.Locals("userId", userSession.UserId)
	//c.Locals("organizationId", c.Locals("organizationId"))

	return c.Next()
}

func requestAccessValidation(c *fiber.Ctx) error {
	// browser tab session - needed for websocket

	browserTabSession := utils.GetBrowserTabSessionHeader(c)

	if len(browserTabSession) == utils.LenHeaderBrowserTabSession {
		c.Locals("browserTabSession", browserTabSession)
	}

	// user session
	xAuthorization := utils.GetXAuhorizationHeader(c)

	if len(xAuthorization) == utils.LenHeaderXAuthorization {
		return userSessionValidation(c)
	}

	// api key
	/*xApiKey := utils.GetXApiKeyHeader(c)

	if len(xApiKey) == utils.LenHeaderXApiKey {
		return userApikeyTokenValidation(c)
	} */

	return c.SendStatus(fiber.StatusUnauthorized)
}

// gets the organization id by subdomain and sets it in the locals
func handleOrganizationSubdomain(c *fiber.Ctx) error {
	host := c.Hostname()

	// split the hostname into parts
	parts := strings.Split(host, ".")

	// check if we have at least three parts (subdomain, domain, tld)
	if len(parts) >= 3 {
		// the first part is the subdomain
		subdomain := parts[0]

		// get organization id by subdomain from database
		organization := models.Organization{}

		database.DB.Select("id").First(&organization, "subdomain = ?", subdomain)

		// if organization not found
		if organization.Id == "" {
			return c.SendStatus(fiber.StatusUnauthorized)
		}

		c.Locals("organizationId", organization.Id)

		return c.Next()
	}

	return c.SendStatus(fiber.StatusBadRequest)
}
