package db

import (
	"github.com/glebarez/sqlite"
	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

type FieldError struct {
}

func Init(dbType string, db string) {
	var err error
	switch dbType {
	case "mysql":
		DB, err = gorm.Open(mysql.Open(db))
	case "sqlite":
		DB, err = gorm.Open(sqlite.Open(db), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Silent),
		})
		migrate()
	default:
		logrus.Fatal("Could not init database, unknown database type")
	}
	if err != nil {
		logrus.Fatalf("failed to connect database: %s", err)
	}
	initConfig()
}

func migrate() {
	err := DB.AutoMigrate(&Config{}, &SpeedingTicket{})
	if err != nil {
		logrus.Fatal(err)
	}
}
