package database

import (
	"log"
	"rrbec_server/internal/models"

	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
)

var DB *gorm.DB

func InitDB(dataSourceName string) *gorm.DB {
	var err error
	DB, err = gorm.Open(sqlite.Open(dataSourceName), &gorm.Config{})
	if err != nil {
		log.Fatalf("failed to connect database: %v", err)
	}

	// Auto Migration
	err = DB.AutoMigrate(
		&models.Mesa{},
		&models.Client{},
		&models.Category{},
		&models.Product{},
		&models.ProductComponent{},
		&models.Comanda{},
		&models.ProductComanda{},
		&models.Order{},
		&models.TypePay{},
		&models.Payment{},
		&models.User{},
		&models.SyncState{},
	)
	if err != nil {
		log.Fatalf("failed to migrate database: %v", err)
	}

	return DB
}
