package main

import (
	"fmt"
	"io/ioutil"
	"os"

	"gopkg.in/yaml.v2"
)

// Define the Config struct
type Config struct {
	DatabasePath     string `yaml:"database_path"`
	TestDatabasePath string `yaml:"test_database_path"`
	JWTSecret        string `yaml:"jwt_secret"`
	ImageStorageDir  string `yaml:"image_storage_dir"`
	ListeningPort    int    `yaml:"listening_port"`
	LogFile          string `yaml:"log_file"`
	StaticFilesDir   string `yaml:"static_files_dir"`
	AllowedOrigins   string `yaml:"allowed_origins"`
}

func LoadConfig(configPath string) (*Config, error) {
	data, err := ioutil.ReadFile(configPath)
	if err != nil {
		return nil, fmt.Errorf("failed to read config file: %v", err)
	}

	var config Config
	err = yaml.Unmarshal(data, &config)
	if err != nil {
		return nil, fmt.Errorf("failed to unmarshal config file: %v", err)
	}

	// Get the database path from environment variables or use the default
	dbPath := os.Getenv("TEST_DATABASE_PATH")
	if dbPath != "" {
		fmt.Println("Using test database path from environment variable:", dbPath)
		config.DatabasePath = dbPath
	}

	if config.StaticFilesDir == "" {
		config.StaticFilesDir = "build"
	}

	if config.AllowedOrigins == "" {
		config.AllowedOrigins = "http://localhost:3000"
	}

	return &config, nil
}
