package processor_test

import (
	"reflect"
	"testing"

	"github.com/jwetzell/showbridge-go/config"
	"github.com/jwetzell/showbridge-go/internal/common"
	"github.com/jwetzell/showbridge-go/internal/processor"
	"github.com/jwetzell/showbridge-go/internal/test"
	_ "modernc.org/sqlite"
)

func TestDbQueryFromRegistry(t *testing.T) {
	registration, ok := processor.GetProcessorRegistration("db.query")
	if !ok {
		t.Fatalf("db.query processor not registered")
	}

	processorInstance, err := registration.New(config.ProcessorConfig{
		Id:   "test-id",
		Type: "db.query",
		Params: map[string]any{
			"module": "test",
			"query":  "SELECT 1;",
		},
	})
	if err != nil {
		t.Fatalf("failed to create db.query processor: %s", err)
	}

	if processorInstance.Id() != "test-id" {
		t.Fatalf("db.query processor has wrong id: %s", processorInstance.Id())
	}

	if processorInstance.Type() != "db.query" {
		t.Fatalf("db.query processor has wrong type: %s", processorInstance.Type())
	}

	payload := "hello"
	expected := map[string]any{"1": int64(1)}

	got, err := processorInstance.Process(t.Context(), common.WrappedPayload{
		Payload: payload,
		Modules: map[string]common.Module{
			"test": test.NewTestDBModule("test"),
		},
	})
	if err != nil {
		t.Fatalf("db.query processing failed: %s", err)
	}

	if !reflect.DeepEqual(got.Payload, expected) {
		t.Fatalf("db.query got %+v, expected %+v", got.Payload, expected)
	}
}

func TestGoodDbQuery(t *testing.T) {

	testCases := []struct {
		name     string
		params   map[string]any
		payload  any
		expected any
	}{
		{
			name: "basic query",
			params: map[string]any{
				"module": "test",
				"query":  "select value from test where id = 1;",
			},
			payload:  "",
			expected: map[string]any{"value": "test-1"},
		},
		{
			name: "template query",
			params: map[string]any{
				"module": "test",
				"query":  "select value from test where id = {{.Payload}};",
			},
			payload:  "1",
			expected: map[string]any{"value": "test-1"},
		},
		{
			name: "multiple rows",
			params: map[string]any{
				"module": "test",
				"query":  "select * from test;",
			},
			payload: "",
			expected: []map[string]any{
				{"id": int64(1), "value": "test-1"},
				{"id": int64(2), "value": "test-2"},
			},
		},
		{
			name: "no rows",
			params: map[string]any{
				"module": "test",
				"query":  "select * from test where id = -1;",
			},
			payload:  "",
			expected: nil,
		},
	}
	for _, testCase := range testCases {
		t.Run(testCase.name, func(t *testing.T) {
			registration, ok := processor.GetProcessorRegistration("db.query")
			if !ok {
				t.Fatalf("db.query processor not registered")
			}

			processorInstance, err := registration.New(config.ProcessorConfig{
				Type:   "db.query",
				Params: testCase.params,
			})

			if err != nil {
				t.Fatalf("db.query failed to create processor: %s", err)
			}

			got, err := processorInstance.Process(t.Context(), common.WrappedPayload{
				Modules: map[string]common.Module{
					"test": test.NewTestDBModule("test"),
				},
				Payload: testCase.payload,
			})

			if err != nil {
				t.Fatalf("db.query processing failed: %s", err)
			}

			if !reflect.DeepEqual(got.Payload, testCase.expected) {
				t.Fatalf("db.query got payload: %+v, expected %+v", got.Payload, testCase.expected)
			}
		})
	}
}

func TestBadDbQuery(t *testing.T) {
	tests := []struct {
		name                  string
		params                map[string]any
		payload               any
		wrappedPayloadModules map[string]common.Module
		errorString           string
	}{
		{
			name:    "no module param",
			payload: test.TestStruct{Data: "hello"},
			params: map[string]any{
				"query": "SELECT sqlite_version();",
			},
			wrappedPayloadModules: map[string]common.Module{
				"test": test.NewTestDBModule("test"),
			},
			errorString: "db.query module error: not found",
		},
		{
			name:    "non string module",
			payload: test.TestStruct{Data: "hello"},
			params: map[string]any{
				"module": 1,
				"query":  "SELECT sqlite_version();",
			},
			wrappedPayloadModules: map[string]common.Module{
				"test": test.NewTestDBModule("test"),
			},
			errorString: "db.query module error: not a string",
		},
		{
			name:    "no query param",
			payload: test.TestStruct{Data: "hello"},
			params: map[string]any{
				"module": "test",
			},
			wrappedPayloadModules: map[string]common.Module{
				"test": test.NewTestDBModule("test"),
			},
			errorString: "db.query query error: not found",
		},
		{
			name:    "non string query",
			payload: test.TestStruct{Data: "hello"},
			params: map[string]any{
				"module": "test",
				"query":  1,
			},
			wrappedPayloadModules: map[string]common.Module{
				"test": test.NewTestDBModule("test"),
			},
			errorString: "db.query query error: not a string",
		},
		{
			name:    "query template syntax error",
			payload: test.TestStruct{Data: "hello"},
			params: map[string]any{
				"module": "test",
				"query":  "select * from {{",
			},
			wrappedPayloadModules: map[string]common.Module{
				"test": test.NewTestDBModule("test"),
			},
			errorString: "template: query:1: unclosed action",
		},
		{
			name:    "query template error",
			payload: test.TestStruct{Data: "hello"},
			params: map[string]any{
				"module": "test",
				"query":  "select * from {{.Data}}",
			},
			wrappedPayloadModules: map[string]common.Module{
				"test": test.NewTestDBModule("test"),
			},
			errorString: "template: query:1:16: executing \"query\" at <.Data>: can't evaluate field Data in type common.WrappedPayload",
		},
		{
			name:    "query error",
			payload: test.TestStruct{Data: "hello"},
			params: map[string]any{
				"module": "test",
				"query":  "select * from asdf;",
			},
			wrappedPayloadModules: map[string]common.Module{
				"test": test.NewTestDBModule("test"),
			},
			errorString: "db.query error executing query: SQL logic error: no such table: asdf (1)",
		},
		{
			name:    "no modules in context",
			payload: test.TestStruct{Data: "hello"},
			params: map[string]any{
				"module": "test",
				"query":  "select * from test;",
			},
			wrappedPayloadModules: nil,
			errorString:           "db.query wrapped payload has no modules",
		},
		{
			name:    "module not found in context",
			payload: test.TestStruct{Data: "hello"},
			params: map[string]any{
				"module": "test",
				"query":  "select * from test;",
			},
			wrappedPayloadModules: map[string]common.Module{},
			errorString:           "db.query unable to find module with id: test",
		},
		{
			name:    "module not a DatabaseModule",
			payload: test.TestStruct{Data: "hello"},
			params: map[string]any{
				"module": "test",
				"query":  "select * from test;",
			},
			wrappedPayloadModules: map[string]common.Module{
				"test": test.NewTestKVModule("test", nil),
			},
			errorString: "db.query module with id test is not a DatabaseModule",
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {

			registration, ok := processor.GetProcessorRegistration("db.query")
			if !ok {
				t.Fatalf("db.query processor not registered")
			}

			processorInstance, err := registration.New(config.ProcessorConfig{
				Type:   "db.query",
				Params: test.params,
			})

			if err != nil {
				if test.errorString != err.Error() {
					t.Fatalf("db.query got error '%s', expected '%s'", err.Error(), test.errorString)
				}
				return
			}

			got, err := processorInstance.Process(t.Context(), common.WrappedPayload{
				Payload: test.payload,
				Modules: test.wrappedPayloadModules,
			})

			if err == nil {
				t.Fatalf("db.query expected to fail but got payload: %+v", got)
			}

			if err.Error() != test.errorString {
				t.Fatalf("db.query got error '%s', expected '%s'", err.Error(), test.errorString)
			}
		})
	}
}

func BenchmarkDbQuery(b *testing.B) {
	registration, ok := processor.GetProcessorRegistration("db.query")
	if !ok {
		b.Fatalf("db.query processor not registered")
	}

	processorInstance, err := registration.New(config.ProcessorConfig{
		Type: "db.query",
		Params: map[string]any{
			"module": "test",
			"query":  "SELECT * FROM test;",
		},
	})

	if err != nil {
		b.Fatalf("db.query failed to create processor: %s", err)
	}
	modules := map[string]common.Module{
		"test": test.NewTestDBModule("test"),
	}

	for b.Loop() {
		_, err := processorInstance.Process(b.Context(), common.WrappedPayload{Payload: nil, Modules: modules})
		if err != nil {
			b.Fatalf("db.query processing failed: %s", err)
		}
	}
}
