/*
 * 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 (
	"errors"
	"io/ioutil"
	"log"

	"gopkg.in/yaml.v3"
)

var (
	cfg Config
)

type Config struct {
	Mysql            *MysqlConfig `yaml:"mysql"`
	Tables           []Table      `yaml:"tables"`
	SqsUrl           string       `yaml:"sqs_url"`
	CentralNamespace string       `yaml:"central_namespace"`
}

func (cfg *Config) FillWithDefaults() {
	cfg.Mysql.FillWithDefaults()
}

func (cfg *Config) Validate() error {
	if len(cfg.SqsUrl) == 0 {
		return errors.New("sqs_url is empty")
	}

	if len(cfg.Tables) == 0 {
		return errors.New("tables is empty")
	}

	if len(cfg.CentralNamespace) == 0 {
		return errors.New("central_namespace is empty")
	}
	dup := make(map[string]struct{})
	for _, tbl := range cfg.Tables {
		if err := tbl.Validate(); err != nil {
			return err
		}
		if _, ok := dup[tbl.MessageGroupID]; ok {
			return errors.New("message_group_id is duplicated")
		} else {
			dup[tbl.MessageGroupID] = struct{}{}
		}
	}
	return nil
}

func InitConfig(cfgPath string) error {
	b, err := ioutil.ReadFile(cfgPath)
	if err != nil {
		log.Println("read file", err)
		return err
	}
	if err := yaml.Unmarshal(b, &cfg); err != nil {
		log.Println("unmarshal yaml file", err)
		return err
	}
	cfg.FillWithDefaults()
	return cfg.Validate()
}
