// Copyright (c) 2021 OceanBase
// obagent is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//
// http://license.coscl.org.cn/MulanPSL2
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.

package mysql

import (
	"os"
	"testing"

	sqle "github.com/dolthub/go-mysql-server"
	"github.com/dolthub/go-mysql-server/auth"
	"github.com/dolthub/go-mysql-server/memory"
	"github.com/dolthub/go-mysql-server/server"
	"github.com/dolthub/go-mysql-server/sql"
)

func TestMain(m *testing.M) {
	s := setup()
	code := m.Run()
	teardown(s)
	os.Exit(code)
}

func setup() *server.Server {
	driver := sqle.NewDefault()
	driver.AddDatabase(createTestDatabase())

	config := server.Config{
		Protocol: "tcp",
		Address:  "0.0.0.0:9876",
		Auth:     auth.NewNativeSingle("user", "pass", auth.AllPermissions),
	}

	s, err := server.NewDefaultServer(config, driver)
	if err != nil {
		panic(err)
	}

	go s.Start()
	return s
}

func createTestDatabase() *memory.Database {
	const (
		dbName    = "test"
		tableName = "test_metric"
	)

	db := memory.NewDatabase(dbName)
	table := memory.NewTable(tableName, sql.Schema{
		{Name: "t1", Type: sql.Text, Nullable: false, Source: tableName},
		{Name: "t2", Type: sql.Text, Nullable: false, Source: tableName},
		{Name: "m1", Type: sql.Float64, Nullable: false, Source: tableName},
		{Name: "m2", Type: sql.Int64, Nullable: false, Source: tableName},
	})

	db.AddTable(tableName, table)
	ctx := sql.NewEmptyContext()

	rows := []sql.Row{
		sql.NewRow("a", "A", 1.0, 1),
		sql.NewRow("b", "B", 2.0, 2),
		sql.NewRow("c", "C", 3.0, 3),
		sql.NewRow("d", "D", 4.0, 4),
	}

	for _, row := range rows {
		table.Insert(ctx, row)
	}

	return db
}

func teardown(s *server.Server) {
	s.Close()
}
