package clickhouse_test

import (
	"testing"

	"github.com/fiskerinc/cloud-services/pkg/clickhouse"
	"github.com/fiskerinc/cloud-services/pkg/testhelper"
)

func TestRetrieveDefaultFilters(t *testing.T) {
	filters := []clickhouse.CANFilterSchema{
		{
			ID:     1,
			Period: 2,
		},
		{
			ID:     3,
			Period: 4,
		},
	}

	conn := &clickhouse.MockConn{ExpectedResult: filters}
	client := clickhouse.NewMockClient(conn)

	defaults, err := client.RetrieveDefaultFilters()
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveDefaultFilters", nil, err)
	}

	for i := range filters {
		if filters[i].ID != defaults[i].ID {
			t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveDefaultFilters", filters[i].ID, defaults[i].ID)
		}
		if filters[i].Period != defaults[i].Period {
			t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveDefaultFilters", filters[i].Period, defaults[i].Period)
		}
	}
}

func TestRetrieveFiltersForVehicle(t *testing.T) {
	filters := []clickhouse.CANFilterSchema{
		{
			ID:     1,
			Period: 2,
		},
		{
			ID:     3,
			Period: 4,
		},
	}

	conn := &clickhouse.MockConn{ExpectedResult: filters}
	client := clickhouse.NewMockClient(conn)

	defaults, err := client.RetrieveFiltersForVehicle("TESTVIN123")
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveDefaultFilters", nil, err)
	}

	for i := range filters {
		if filters[i].ID != defaults[i].ID {
			t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveDefaultFilters", filters[i].ID, defaults[i].ID)
		}
		if filters[i].Period != defaults[i].Period {
			t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveDefaultFilters", filters[i].Period, defaults[i].Period)
		}
	}
}

func TestCreateDBCSignalQuery(t *testing.T) {

	tests := []struct {
		name   string
		input  clickhouse.PageQueryOptions
		result string
		err    error
	}{
		{
			name: "with no options",
			input: clickhouse.PageQueryOptions{
				Limit:  0,
				Offset: 0,
			},
			result: `select * from dbc_signals where dbc_hash = {dbc:String}`,
			err: nil,
		},
		{
			name: "with the offset option",
			input: clickhouse.PageQueryOptions{
				Limit:  0,
				Offset: 10,
			},
			result: `select * from dbc_signals where dbc_hash = {dbc:String} OFFSET {offs:UInt64}`,
			err: nil,
		},
		{
			name: "with the limit option",
			input: clickhouse.PageQueryOptions{
				Limit:  10,
				Offset: 0,
			},
			result: `select * from dbc_signals where dbc_hash = {dbc:String} LIMIT {lim:UInt64}`,
			err: nil,
		},
		{
			name: "with the offset and limit options",
			input: clickhouse.PageQueryOptions{
				Limit:  100,
				Offset: 10,
			},
			result: `select * from dbc_signals where dbc_hash = {dbc:String} LIMIT {lim:UInt64} OFFSET {offs:UInt64}`,
			err: nil,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			ans := clickhouse.CreateDBCSignalQuery(test.input)
			if ans != test.result {
				t.Errorf("got %s, expected %s", ans, test.result)
			}
		})
	}

}
