package initializers

import (
	"log"
	"os"

	"gitea.tbdevent.eu/TBD/reforger_crawler_main/models"
	"gopkg.in/yaml.v3"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

var DB *gorm.DB
var PORT string
var IP string
var SECRET string
var DB_NAME string
var DiscordWebhook string
var ADMIN_SECRET string

func ConnectToDB() {
	db, err := gorm.Open(sqlite.Open(DB_NAME), &gorm.Config{})
	if err != nil {
		log.Fatal("Failed to connect to database")
	}

	DB = db

	DB.AutoMigrate(&models.Addon{}, &models.AddonFile{})
}

type Configuration struct {
	Port   string `yaml:"port"`
	IP     string `yaml:"ip"`
	Secret string `yaml:"secret"`
	DB     string `yaml:"db"`
	DiscordWebhook string `yaml:"discordWebhook"`
	ADMIN_SECRET string `yaml:"adminSecret"`
}

func Load() {
file, err := os.ReadFile("config.yaml")
	if err != nil {
		log.Fatal("Failed to open config file")
	}

	configuration := Configuration{
		DB: "register.db",
	}
	err = yaml.Unmarshal(file, &configuration)
	if err != nil {
		log.Fatal("Failed to read yaml file")
	}

	PORT = configuration.Port
	IP = configuration.IP
	SECRET = configuration.Secret
	DB_NAME = configuration.DB
	DiscordWebhook = configuration.DiscordWebhook
	ADMIN_SECRET = configuration.ADMIN_SECRET
}
