package repository

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

func TestNewSqliteDB(t *testing.T) {
	dbPath := os.Getenv("TEST_DB")
	//	sql_driver.MakeTables(dbFile)
	ctx := context.Background()
	sqliteDb, err := sqlite_queue.OpenSqliteDb(dbPath)
	assert.NoError(t, err)

	queue, err := sqlite_queue.NewQueue(ctx, sqliteDb)
	assert.NoError(t, err)

	queue.Start()
	defer queue.Stop()
	db := NewSqliteRepository(ctx, queue)
	assert.NoError(t, err)
	testSignupLoginRenew(t, &db)
	testSqliteDBRandomSvgInterface(t, &db)
}

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())
}
