package postgres

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

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

func (s *Repository) BudgetsForUser(id string) ([]*budgeteer.Budget, error) {
	user := &budgeteer.User{
		ID: id,
	}
	err := s.DB.Model(&user).
		Column("user.*", "Budgets").
		Select()
	if err != nil {
		return nil, err
	}
	return user.Budgets, nil

}

func (s *Repository) NewBudget(name string, userID string) (*budgeteer.Budget, error) {
	b := &budgeteer.Budget{ID: s.IDGenerator.New(), Name: name}
	err := s.DB.Insert(b)
	if err != nil {
		return nil, err
	}

	ub := &budgeteer.UserBudget{UserID: userID, BudgetID: b.ID}
	err = s.DB.Insert(ub)
	if err != nil {
		return nil, err
	}

	return b, nil
}
