package auth

import (
	"errors"

	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"

	"reichard.io/imagini/graph/model"
	"reichard.io/imagini/internal/config"
	"reichard.io/imagini/internal/db"
)

type AuthManager struct {
	DB     *db.DBManager
	Config *config.Config
}

func NewMgr(db *db.DBManager, c *config.Config) *AuthManager {
	return &AuthManager{
		DB:     db,
		Config: c,
	}
}

func (auth *AuthManager) AuthenticateUser(user, password string) (model.User, bool) {
	// Find User by Username / Email
	foundUser := &model.User{Username: user}
	_, err := auth.DB.User(foundUser)

	// By Username
	if errors.Is(err, gorm.ErrRecordNotFound) {
		foundUser = &model.User{Email: user}
		_, err = auth.DB.User(foundUser)
	}

	// By Email
	if errors.Is(err, gorm.ErrRecordNotFound) {
		log.Warn("[auth] User not found: ", user)
		return *foundUser, false
	} else if err != nil {
		log.Error(err)
		return *foundUser, false
	}

	log.Info("[auth] Authenticating user: ", foundUser.Username)

	// Determine Type
	switch foundUser.AuthType {
	case "Local":
		return *foundUser, authenticateLocalUser(*foundUser, password)
	case "LDAP":
		return *foundUser, authenticateLDAPUser(*foundUser, password)
	default:
		return *foundUser, false
	}
}
