package main

import (
	"net/http"

	"git.haelnorr.com/h/golib/hws"
	"git.haelnorr.com/h/golib/hwsauth"
	"github.com/pkg/errors"
	"github.com/uptrace/bun"

	"git.haelnorr.com/h/oslstats/internal/config"
	"git.haelnorr.com/h/oslstats/internal/db"
	"git.haelnorr.com/h/oslstats/internal/discord"
	"git.haelnorr.com/h/oslstats/internal/handlers"
	"git.haelnorr.com/h/oslstats/internal/store"
)

func addRoutes(
	server *hws.Server,
	staticFS *http.FileSystem,
	cfg *config.Config,
	conn *bun.DB,
	auth *hwsauth.Authenticator[*db.User, bun.Tx],
	store *store.Store,
	discordAPI *discord.APIClient,
) error {
	// Create the routes
	routes := []hws.Route{
		{
			Path:    "/static/",
			Method:  hws.MethodGET,
			Handler: http.StripPrefix("/static/", handlers.StaticFS(staticFS, server)),
		},
		{
			Path:    "/",
			Method:  hws.MethodGET,
			Handler: handlers.Index(server),
		},
		{
			Path:    "/login",
			Method:  hws.MethodGET,
			Handler: auth.LogoutReq(handlers.Login(server, cfg, store, discordAPI)),
		},
		{
			Path:    "/auth/callback",
			Method:  hws.MethodGET,
			Handler: auth.LogoutReq(handlers.Callback(server, auth, conn, cfg, store, discordAPI)),
		},
		{
			Path:    "/register",
			Methods: []hws.Method{hws.MethodGET, hws.MethodPOST},
			Handler: auth.LogoutReq(handlers.Register(server, auth, conn, cfg, store)),
		},
		{
			Path:    "/logout",
			Methods: []hws.Method{hws.MethodGET, hws.MethodPOST},
			Handler: auth.LoginReq(handlers.Logout(server, auth, conn, discordAPI)),
		},
		{
			Path:    "/test",
			Methods: []hws.Method{hws.MethodGET, hws.MethodPOST},
			Handler: handlers.Test(server),
		},
	}

	htmxRoutes := []hws.Route{
		{
			Path:    "/htmx/isusernameunique",
			Method:  hws.MethodPOST,
			Handler: handlers.IsUsernameUnique(server, conn, cfg, store),
		},
	}

	// Register the routes with the server
	err := server.AddRoutes(append(routes, htmxRoutes...)...)
	if err != nil {
		return errors.Wrap(err, "server.AddRoutes")
	}
	return nil
}
