package app

import (
	"fmt"

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

func (a *App) CreateUser(username, password, name, mail string, admin bool) (*model.User, error) {
	hashedPassword, err := utils.Encrypt(password)
	if err != nil {
		return nil, fmt.Errorf("cannot create user: %w", err)
	}

	newUser := &model.User{
		Username: username,
		Password: hashedPassword,
		Name:     name,
		Mail:     mail,
		Admin:    admin,
	}

	if err := newUser.IsValid(); err != nil {
		return nil, fmt.Errorf("invalid user for creation: %w", err)
	}

	return a.Store.User().Create(newUser)
}

func (a *App) ListUsers() ([]*model.User, error) {
	return a.Store.User().List()
}

func (a *App) DeleteUserByUsername(username string) error {
	return a.Store.User().DeleteByUsername(username)
}

func (a *App) GetUserByUsername(username string) (*model.User, error) {
	return a.Store.User().GetByUsername(username)
}

func (a *App) GetUserByID(userID int) (*model.User, error) {
	return a.Store.User().GetByID(userID)
}
