package main

import (
	"context"

	"git.haelnorr.com/h/golib/hlog"
	"git.haelnorr.com/h/golib/hws"
	"git.haelnorr.com/h/golib/hwsauth"
	"git.haelnorr.com/h/oslstats/internal/db"
	"git.haelnorr.com/h/oslstats/internal/handlers"
	"github.com/pkg/errors"
	"github.com/uptrace/bun"
)

func setupAuth(
	config *hwsauth.Config,
	logger *hlog.Logger,
	conn *bun.DB,
	server *hws.Server,
	ignoredPaths []string,
) (*hwsauth.Authenticator[*db.User, bun.Tx], error) {
	beginTx := func(ctx context.Context) (hwsauth.DBTransaction, error) {
		tx, err := conn.BeginTx(ctx, nil)
		return tx, err
	}
	auth, err := hwsauth.NewAuthenticator(
		config,
		db.GetUserByID,
		server,
		beginTx,
		logger,
		handlers.ErrorPage,
		conn.DB,
	)
	if err != nil {
		return nil, errors.Wrap(err, "hwsauth.NewAuthenticator")
	}

	auth.IgnorePaths(ignoredPaths...)

	db.CurrentUser = auth.CurrentModel

	return auth, nil
}

// TODO: make a new getuser function that wraps db.GetUserByID and does OAuth refresh
