package models

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

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

	// Bootstrap our test publisher
	testpublisher := Publisher{
		Name: "Testpublisher",
	}

	// Delete every prexisting publisher to have a fresh start
	allpublishers, err := ListPublishers("")
	assert.NoError(t, err)

	for _, publisher := range allpublishers {

		// Delete
		err = DeletePublisherByID(publisher.ID)
		assert.NoError(t, err)

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

	// Create a new publisher
	publisher1, err := AddOrUpdatePublisher(testpublisher)
	assert.NoError(t, err)
	assert.Equal(t, testpublisher.Name, publisher1.Name)

	// Get the new publisher
	gotpublisher, exists, err := GetPublisherByID(publisher1.ID)
	assert.NoError(t, err)
	assert.True(t, exists)
	assert.Equal(t, testpublisher.Name, gotpublisher.Name)

	// Pass an empty publisher to see if it fails
	_, err = AddOrUpdatePublisher(Publisher{})
	assert.Error(t, err)
	assert.True(t, IsErrNoPublisherName(err))

	// Update the publisher
	testpublisher.ID = publisher1.ID
	testpublisher.Name = "Lorem Ipsum"
	publisher1updated, err := AddOrUpdatePublisher(testpublisher)
	assert.NoError(t, err)
	assert.Equal(t, testpublisher.Name, publisher1updated.Name)

	// Search
	allpublishers, err = ListPublishers("rem")
	assert.NoError(t, err)
	assert.NotNil(t, allpublishers[0])

	// Delete the publisher
	err = DeletePublisherByID(publisher1.ID)
	assert.NoError(t, err)

	// Check if it is gone
	_, exists, err = GetPublisherByID(publisher1.ID)
	assert.NoError(t, err)
	assert.False(t, exists)

	// Try deleting one with ID = 0
	err = DeletePublisherByID(0)
	assert.Error(t, err)
	assert.True(t, IsErrIDCannotBeZero(err))
}
