/*
 * Copyright 2021 PingCAP, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package main

import (
	"testing"

	"github.com/stretchr/testify/require"
	"gopkg.in/yaml.v3"
)

func TestConfig(t *testing.T) {
	var input = `
---
mysql:
  dsn: root:root@tcp(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local
  max_open_conns: 20
  max_idle_conns: 10
  max_life_conns: 60
  trace_include_not_found: false
tables:
  - name: t1
    message_group_id: g1
    column:
      - c1
      - c2
  - name: t2
    message_group_id: g2
    column:
      - c3
      - c4
sqs_url: <whatever>
central_namespace: nightly
`
	assert := require.New(t)
	b := []byte(input)
	assert.Nil(yaml.Unmarshal(b, &cfg))
	assert.Equal("root:root@tcp(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", cfg.Mysql.DSN)
	assert.Equal(20, cfg.Mysql.MaxOpenConns)
	assert.Equal(10, cfg.Mysql.MaxIdleConns)
	assert.Equal(60, cfg.Mysql.MaxLifeConns)
	assert.Equal(2, len(cfg.Tables))
	assert.Equal("t2", cfg.Tables[1].Name)
	assert.Equal("c3", cfg.Tables[1].Column[0])
	assert.Equal("c4", cfg.Tables[1].Column[1])
	assert.Equal("nightly", cfg.CentralNamespace)

}

func TestConfig_Validate(t *testing.T) {
	var input = `
---
mysql:
  dsn: root:root@tcp(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local
  max_open_conns: 20
  max_idle_conns: 10
  max_life_conns: 60
  trace_include_not_found: false
tables:
  - name: t1
	message_group_id: g1
    column:
      - c1
      - c2
  - name: t2
    message_group_id: g1
    column:
      - c3
      - c4
sqs_url: <whatever>
`
	assert := require.New(t)
	b := []byte(input)
	err := yaml.Unmarshal(b, &cfg)
	assert.NotNil(err)
}

func TestMysqlConfig_MergePWD(t *testing.T) {
	var input = `
---
need_merge_pwd: true
dsn: root:__PWD__@tcp(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local
max_open_conns: 20
max_idle_conns: 10
max_life_conns: 60
trace_include_not_found: false`
	assert := require.New(t)
	mysqlCfg := MysqlConfig{}
	assert.Nil(yaml.Unmarshal([]byte(input), &mysqlCfg))
	assert.True(mysqlCfg.NeedMergePWD)
	mysqlCfg.MergePWD("root")
	assert.Equal("root:root@tcp(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", mysqlCfg.DSN)
}
