package main

import (
	"io/fs"
	"net/http"

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

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

func setupHttpServer(
	staticFS *fs.FS,
	cfg *config.Config,
	logger *hlog.Logger,
	bun *bun.DB,
	store *store.Store,
	discordAPI *discord.APIClient,
) (server *hws.Server, err error) {
	if staticFS == nil {
		return nil, errors.New("No filesystem provided")
	}
	fs := http.FS(*staticFS)
	httpServer, err := hws.NewServer(cfg.HWS)
	if err != nil {
		return nil, errors.Wrap(err, "hws.NewServer")
	}

	ignoredPaths := []string{
		"/static/css/output.css",
		"/static/favicon.ico",
	}

	auth, err := setupAuth(cfg.HWSAuth, logger, bun, httpServer, ignoredPaths)
	if err != nil {
		return nil, errors.Wrap(err, "setupAuth")
	}

	err = httpServer.AddErrorPage(handlers.ErrorPage)
	if err != nil {
		return nil, errors.Wrap(err, "httpServer.AddErrorPage")
	}

	err = httpServer.AddLogger(logger)
	if err != nil {
		return nil, errors.Wrap(err, "httpServer.AddLogger")
	}

	err = httpServer.LoggerIgnorePaths(ignoredPaths...)
	if err != nil {
		return nil, errors.Wrap(err, "httpServer.LoggerIgnorePaths")
	}

	err = addRoutes(httpServer, &fs, cfg, bun, auth, store, discordAPI)
	if err != nil {
		return nil, errors.Wrap(err, "addRoutes")
	}

	err = addMiddleware(httpServer, auth, cfg.Flags)
	if err != nil {
		return nil, errors.Wrap(err, "addMiddleware")
	}

	return httpServer, nil
}
