package models

import (
	"github.com/stretchr/testify/assert"
	"testing"
)

func TestAddOrUpdateAuthor(t *testing.T) {
	// Create test database
	assert.NoError(t, PrepareTestDatabase())

	// TODO delete all existing authors from eventual previuous tests

	// Bootstrap our test author
	testauthor := Author{Forename: "test", Lastname: "tsting"}

	// Create a new author
	author1, err := AddOrUpdateAuthor(testauthor)
	assert.NoError(t, err)
	assert.Equal(t, testauthor.Forename, author1.Forename)
	assert.Equal(t, testauthor.Lastname, author1.Lastname)

	// And anotherone
	author2, err := AddOrUpdateAuthor(testauthor)
	assert.NoError(t, err)
	assert.Equal(t, testauthor.Forename, author2.Forename)
	assert.Equal(t, testauthor.Lastname, author2.Lastname)

	// As of now, we should have 2 authors in total. Get the list and check.
	allauthors, err := ListAuthors("")
	assert.NoError(t, err)

	for _, author := range allauthors {
		assert.Equal(t, testauthor.Forename, author.Forename)
		assert.Equal(t, testauthor.Lastname, author.Lastname)
	}

	// Get the new author
	gotauthor, exists, err := GetAuthorByID(author1.ID)
	assert.NoError(t, err)
	assert.True(t, exists)
	assert.Equal(t, gotauthor.Forename, testauthor.Forename)
	assert.Equal(t, gotauthor.Lastname, testauthor.Lastname)

	// Pass an empty author to see if it fails
	_, err = AddOrUpdateAuthor(Author{})
	assert.Error(t, err)

	// Update the author
	testauthor.ID = author1.ID
	testauthor.Forename = "Lorem Ipsum"
	author1updated, err := AddOrUpdateAuthor(testauthor)
	assert.NoError(t, err)
	assert.Equal(t, testauthor.Forename, author1updated.Forename)
	assert.Equal(t, testauthor.Lastname, author1updated.Lastname)

	// Delete the author
	err = DeleteAuthorByID(author1.ID)
	assert.NoError(t, err)

	// Check if it is gone
	_, exists, err = GetAuthorByID(author1.ID)
	assert.NoError(t, err)
	assert.False(t, exists)
}
