// Package auth is responsible for everything authentication
//
// Be that checking login data and handing out an access token on sucess,
// checking if a given access token can do the requested action
// or adding or updating the authentication information of an account.
// And I probably forgot something
package auth

import (
	"time"

	"git.mstar.dev/mstar/goutils/other"
	"github.com/go-webauthn/webauthn/webauthn"
)

// An Authenticator is used for authenticating user requests against the server
type Authenticator struct {
	webauthn               *webauthn.WebAuthn
	recentlyUsedTotpTokens map[string]time.Time
}

// The next state of a login process
type LoginNextState uint8

const (
	LoginNextFailure    LoginNextState = 0         // Login failed (default state)
	LoginNextSucess     LoginNextState = 1 << iota // Login suceeded
	LoginUnknown                                   // Unknown login method type, should result in failure
	LoginNext2FaTotp                               // Login requires a totp token next as 2fa response
	LoginNext2FaPasskey                            // Login requires a passkey token next as 2fa response
	LoginNext2FaMail                               // Login requires an email token next as 2fa response
	LoginStartPassword                             // Login starts with a password
	LoginStartPasskey                              // Login starts with a passkey
)

// Create a new authenticator
func New(webauthnConfig *webauthn.Config) (*Authenticator, error) {
	webauthn, err := webauthn.New(webauthnConfig)
	if err != nil {
		return nil, other.Error("auth", "failed to create webauthn handler", err)
	}
	return &Authenticator{
		webauthn:               webauthn,
		recentlyUsedTotpTokens: make(map[string]time.Time),
	}, nil
}
