package postgres

import "git.javil.eu/jacob1123/budgeteer"

// User returns a user for a given id.
func (s *Repository) User(id string) (*budgeteer.User, error) {
	u := &budgeteer.User{ID: id}
	err := s.DB.Select(&u)
	if err != nil {
		return nil, err
	}
	return u, nil
}

// UserByUsername returns a user for a given username.
func (s *Repository) UserByUsername(username string) (*budgeteer.User, error) {
	u := &budgeteer.User{Email: username}
	err := s.DB.Model(&u).
		Where("email = ?", username).
		Limit(1).
		Select()
	if err != nil {
		return nil, err
	}
	return u, nil
}

// CreateUser saves a user to the DB
func (s *Repository) CreateUser(user *budgeteer.User) error {
	user.ID = s.IDGenerator.New()
	return s.DB.Insert(user)
}
