package models

import "fmt"

// AddOrUpdateAuthor adds a new author based on an author struct
func AddOrUpdateAuthor(author Author) (newAuthor Author, err error) {

	// If the ID is 0, insert the author, otherwise update it
	if author.ID == 0 {
		// Check if the author is empty, only insert it if not
		if author.Forename == "" && author.Lastname == "" {
			return Author{}, fmt.Errorf("Author cannot be empty")
		}
		_, err = x.Insert(&author)

		if err != nil {
			return Author{}, err
		}
	} else {
		_, err = x.Where("id = ?", author.ID).Update(&author)

		if err != nil {
			return Author{}, err
		}
	}

	// Get the newly inserted author
	newAuthor = author

	return newAuthor, err
}
