package config

import (
	"encoding/json"
	"fmt"
	"os"
	"os/user"
	"path/filepath"
)
type Field struct {
	Name         string      `json:"name"`
	Type         string      `json:"type"`
	PrimaryKey   bool        `json:"primary_key,omitempty"`
	ForeignKey   string      `json:"foreign_key,omitempty"`
	Unique       bool        `json:"unique,omitempty"`
	NotNull      bool        `json:"not_null,omitempty"`
	AutoIncrement bool       `json:"auto_increment,omitempty"`
	DefaultValue interface{} `json:"default_value,omitempty"`
}

type TableModel struct {
	Fields []Field `json:"fields"`
}

type DatasmithConfig struct {
	Name string 									`yaml:"name"`
	Version string 								`yaml:"version"`
	CreatedAt string 						`yaml:"created_at"`
	DbType string              		`yaml:"database_type"`
	Tables map[string]TableModel 	`yaml:"tables"`
}


type Configuration struct {
	User string `json:"author"`
}

var Config Configuration
var configPath string

func LoadConfig() {
	usr, err := user.Current()
	if err != nil {
		fmt.Println("Error getting current user:", err)
		return
	}

	configPath = filepath.Join(usr.HomeDir, ".ds-config")

	file, err := os.Open(configPath)
	if err != nil {
		if os.IsNotExist(err) {
			return
		}
		fmt.Println("Error opening config file:", err)
		return
	}
	defer file.Close()

	decoder := json.NewDecoder(file)
	if err := decoder.Decode(&Config); err != nil {
		fmt.Println("Error decoding config file:", err)
	}
}

func SaveConfig() {
	file, err := os.Create(configPath)
	if err != nil {
		fmt.Println("Error creating config file:", err)
		return
	}
	defer file.Close()

	encoder := json.NewEncoder(file)
	if err := encoder.Encode(&Config); err != nil {
		fmt.Println("Error encoding config file:", err)
	}
}