package auth

import (
	"time"

	"git.mstar.dev/mstar/goutils/other"
	"gorm.io/gorm"

	"git.mstar.dev/mstar/linstrom/storage-new/dbgen"
	"git.mstar.dev/mstar/linstrom/storage-new/models"
)

// Check whether a given access token is valid (exists and hasn't expired).
// If it is, returns the user it belongs to
func (a *Authenticator) IsValidAccessToken(token string) (*models.User, error) {
	dbToken, err := dbgen.AccessToken.GetTokenIfValid(token)
	switch err {
	case nil:
		if dbToken.ExpiresAt.Before(time.Now()) {
			return nil, ErrTokenExpired
		} else {
			return &dbToken.User, nil
		}
	case gorm.ErrRecordNotFound:
		return nil, ErrTokenNotFound
	default:
		return nil, other.Error("auth", "failed to check for token", err)
	}
}
