package main

import (
	"fmt"
	"io/ioutil"
	"sync"

	"gopkg.in/yaml.v2"
)

type Config struct {
	CallNo            string `yaml:"call_no"`
	ServerAddress     string `yaml:"server_address"`
	MaxRetries        int    `yaml:"max_retries"`
	ReconnectInterval int    `yaml:"reconnect_interval"`
	ReadTimeout       int    `yaml:"read_timeout"`
	RestAPIEndpoint   string `yaml:"rest_api_endpoint"`
	RestAPIGetDevice  string `yaml:"rest_api_get_device"`
}

var (
	config      Config
	configMutex sync.RWMutex
)

func loadConfig() error {
	configMutex.Lock()
	defer configMutex.Unlock()

	data, err := ioutil.ReadFile("config.yaml")
	if err != nil {
		return err
	}

	if err := yaml.Unmarshal(data, &config); err != nil {
		return err
	}

	return validateConfig(&config)
}

func validateConfig(cfg *Config) error {
	if cfg.CallNo == "" || cfg.ServerAddress == "" || cfg.RestAPIEndpoint == "" {
		return fmt.Errorf("missing required configuration")
	}
	return nil
}

func updateConfigFile(newPhoneNumber string) error {
	configMutex.Lock()
	defer configMutex.Unlock()

	config.CallNo = newPhoneNumber

	data, err := yaml.Marshal(&config)
	if err != nil {
		return fmt.Errorf("failed to marshal config: %v", err)
	}

	if err := ioutil.WriteFile("config.yaml", data, 0644); err != nil {
		return fmt.Errorf("failed to write config file: %v", err)
	}

	return nil
}
