package models

import "fmt"

type BookPublisher struct {
	Book `xorm:"extends"`
	Publisher `xorm:"extends"`
}

func ListBooks(searchterm string) (books []*Book, err error) {

	if searchterm == "" {
		err = x.Table("books").
		//Join("INNER", "publishers", "books.publisher = publishers.id").
			Find(&books)
		if err != nil {
			fmt.Println("Error getting Books", err)
		}
	} else {
		err = x.Where("title LIKE ?", "%" + searchterm + "%").Find(&books)
		if err != nil {
			fmt.Println("Error getting Books", err)
		}
	}


	// Get all authors and publishers
	for i, book := range books {

		// Get publisher
		publisher := Publisher{ID: book.Publisher}
		_, err := x.Get(&publisher)
		if err != nil {
			fmt.Println("Error getting publisher:", err)
		}
		books[i].PublisherFull = publisher

		// Get all authors
		var authors []Author
		err = x.
		Table("authors_books").
			Join("INNER", "authors", "authors_books.author_id = authors.id").
			Where("book_id = ?", book.ID).
			Find(&authors)

		if err != nil {
			fmt.Println("Error getting authors:", err)
		}

		books[i].Authors = authors
	}

	return books, err
}
