package repositories

import (
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"os"

	"git.dynamicdiscord.de/kalipso/zineshop/models"
)

var (
	ShopItems     ShopItemRepository
	Users         UserRepository
	Tags          TagRepository
	CartItems     CartItemRepository
	Orders        OrderRepository
	Tokens        RegisterTokenRepository
	ConfigOptions ConfigRepository
	Papers        PaperRepository
	PrintJobs     PrintJobRepository
	Invoices      InvoiceRepository
)

func InitRepositories() {
	db, err := gorm.Open(sqlite.Open(os.Getenv("SQLITE_DB")), &gorm.Config{})
	if err != nil {
		panic("failed to connect to database")
	}

	err = db.AutoMigrate(&models.ShopItem{},
		&models.ItemVariant{},
		&models.User{},
		&models.Tag{},
		&models.CartItem{},
		&models.Order{},
		&models.Config{},
		&models.Paper{},
		&models.PrintJob{},
		&models.Invoice{},
		&models.RegisterToken{})

	if err != nil {
		panic("failed to migrate database")
	}

	ShopItems = NewGORMShopItemRepository(db)
	Users = NewGORMUserRepository(db)
	Tags = NewGORMTagRepository(db)
	CartItems = NewGORMCartItemRepository(db)
	Orders = NewGORMOrderRepository(db)
	Tokens = NewGORMRegisterTokenRepository(db)
	ConfigOptions = NewGORMConfigRepository(db)
	Papers = NewGORMPaperRepository(db)
	PrintJobs = NewGORMPrintJobRepository(db)
	Invoices = NewGORMInvoiceRepository(db)
}
