// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.
// All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package auth

import (
	"fmt"
	"log/slog"
	"net/http"

	"git.clustercockpit.org/moebiusband/go-http-skeleton/internal/repository"
	"golang.org/x/crypto/bcrypt"
)

type LocalAuthenticator struct {
	auth *Authentication
}

var _ Authenticator = (*LocalAuthenticator)(nil)

func (la *LocalAuthenticator) Init() error {
	return nil
}

func (la *LocalAuthenticator) CanLogin(
	user *repository.AppUser,
	username string,
	rw http.ResponseWriter,
	r *http.Request,
) (*repository.AppUser, bool) {
	return user, user != nil
}

func (la *LocalAuthenticator) Login(
	user *repository.AppUser,
	rw http.ResponseWriter,
	r *http.Request,
) (*repository.AppUser, error) {
	if e := bcrypt.CompareHashAndPassword([]byte(*user.UserPass),
		[]byte(r.FormValue("password"))); e != nil {
		slog.Error("AUTH/LOCAL > Authentication for user failed!", "user", user.UserName)
		return nil, fmt.Errorf("Authentication failed")
	}

	return user, nil
}
