package app

import (
	"database/sql"
	"fmt"

	"git.ctrlz.es/mgdelacroix/craban/utils"
)

func (a *App) Login(username, password string) (string, error) {
	user, err := a.Store.User().GetByUsername(username)
	if err == sql.ErrNoRows {
		return "", nil
	} else if err != nil {
		return "", fmt.Errorf("cannot get user by username: %w", err)
	}

	if !utils.CheckHash(user.Password, password) {
		return "", nil
	}

	token, err := utils.GenerateToken(user.ID, *a.Config.Secret)
	if err != nil {
		return "", fmt.Errorf("cannot generate token: %w", err)
	}

	return token, nil
}
