package db

import (
	"github.com/stretchr/testify/assert"
	"go-nkode/internal/entities"
	"go-nkode/internal/models"
	"os"
	"testing"
)

func TestNewSqliteDB(t *testing.T) {
	dbFile := os.Getenv("TEST_DB")
	//	sql_driver.MakeTables(dbFile)
	db, err := NewSqliteDB(dbFile)
	assert.NoError(t, err)
	defer db.Close()

	testSignupLoginRenew(t, db)
	testSqliteDBRandomSvgInterface(t, db)
	//	if _, err := os.Stat(dbFile); err == nil {
	//		err = os.Remove(dbFile)
	//		assert.NoError(t, err)
	//	} else {
	//		assert.NoError(t, err)
	//	}
}

func testSignupLoginRenew(t *testing.T, db CustomerUserRepository) {
	nkodePolicy := models.NewDefaultNKodePolicy()
	customerOrig, err := entities.NewCustomer(nkodePolicy)
	assert.NoError(t, err)
	err = db.CreateCustomer(*customerOrig)
	assert.NoError(t, err)
	customer, err := db.GetCustomer(customerOrig.Id)
	assert.NoError(t, err)
	assert.Equal(t, customerOrig, customer)
	username := "test_user@example.com"
	kp := entities.KeypadDefault
	passcodeIdx := []int{0, 1, 2, 3}
	mockSvgInterface := make(models.SvgIdInterface, kp.TotalAttrs())
	ui, err := entities.NewUserInterface(&kp, mockSvgInterface)
	assert.NoError(t, err)
	userOrig, err := entities.NewUser(*customer, username, passcodeIdx, *ui, kp)
	assert.NoError(t, err)
	err = db.WriteNewUser(*userOrig)
	assert.NoError(t, err)
	user, err := db.GetUser(models.UserEmail(username), customer.Id)
	assert.NoError(t, err)
	assert.Equal(t, userOrig, user)

	err = db.Renew(customer.Id)
	assert.NoError(t, err)

}

func testSqliteDBRandomSvgInterface(t *testing.T, db CustomerUserRepository) {
	kp := entities.KeypadMax
	svgs, err := db.RandomSvgInterface(kp)
	assert.NoError(t, err)
	assert.Len(t, svgs, kp.TotalAttrs())
}
