package models

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

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

	// Bootstrap our test item
	testitem := Item{
		Title:       "Testitem",
		Price:       9.999,
		Description: "Lorem Ipsum",
		Other:       "bs",
	}

	// Create a new item
	item1, err := AddOrUpdateItem(testitem)
	assert.NoError(t, err)
	assert.Equal(t, testitem.Title, item1.Title)
	assert.Equal(t, testitem.Price, item1.Price)
	assert.Equal(t, testitem.Description, item1.Description)
	assert.Equal(t, testitem.Other, item1.Other)

	// And anotherone
	item2, err := AddOrUpdateItem(testitem)
	assert.NoError(t, err)
	assert.Equal(t, testitem.Title, item2.Title)

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

	for _, item := range allitems {
		assert.Equal(t, testitem.Title, item.Title)
		assert.Equal(t, testitem.Price, item.Price)
		assert.Equal(t, testitem.Description, item.Description)
		assert.Equal(t, testitem.Other, item.Other)
	}

	// Get the new item
	gotitem, exists, err := GetItemByID(item1.ID)
	assert.NoError(t, err)
	assert.True(t, exists)
	assert.Equal(t, testitem.Title, gotitem.Title)
	assert.Equal(t, testitem.Price, gotitem.Price)
	assert.Equal(t, testitem.Description, gotitem.Description)
	assert.Equal(t, testitem.Other, gotitem.Other)

	// Pass an empty item to see if it fails
	_, err = AddOrUpdateItem(Item{})
	assert.Error(t, err)

	// Update the item
	testitem.ID = item1.ID
	testitem.Title = "Lorem Ipsum"
	item1updated, err := AddOrUpdateItem(testitem)
	assert.NoError(t, err)
	assert.Equal(t, testitem.Title, item1updated.Title)
	assert.Equal(t, testitem.Price, item1updated.Price)
	assert.Equal(t, testitem.Description, item1updated.Description)
	assert.Equal(t, testitem.Other, item1updated.Other)

	// Test Quantity
	qty1, err := item1.getQuantity()
	assert.NoError(t, err)
	assert.Equal(t, item1.Quantity, qty1)

	// Update the quantity and check again
	err = item1.setQuantity(int64(99))
	assert.NoError(t, err)

	qty2, err := item1.getQuantity()
	assert.NoError(t, err)
	assert.Equal(t, int64(99), qty2)

	// Delete the item
	err = DeleteItemByID(item1.ID)
	assert.NoError(t, err)

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