package models

import (
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB
var phaseOneID uint

func ConnectDatabaseDev() {
	database, err := gorm.Open(sqlite.Open("dev.db"), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Warn),
	})
	if err != nil {
		panic("Couldn't connect to database")
	}

	database.AutoMigrate(&Card{}, &CardDeck{}, &Phase{}, &User{})

	DB = database
}
func ConnectDatabase() {
	database, err := gorm.Open(sqlite.Open("dev.db"), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Warn),
	})
	if err != nil {
		panic("Couldn't connect to database")
	}

	database.AutoMigrate(&Card{}, &CardDeck{}, &Phase{}, &User{})

	DB = database
}

func SeedDatabase() {

	var phaseCount int64
	var phaseOne Phase
	if DB.Table("phases").Count(&phaseCount); phaseCount == 0 {
		phaseFive := Phase{
			Name:        "Phase 5",
			PauseLength: 90,
		}
		phaseFour := Phase{
			Name:        "Phase 4",
			PauseLength: 30,
		}
		phaseThree := Phase{
			Name:        "Phase 3",
			PauseLength: 14,
		}
		phaseTwo := Phase{
			Name:        "Phase 2",
			PauseLength: 7,
		}
		phaseOne = Phase{
			Name:        "Phase 1",
			PauseLength: 3,
		}
		DB.Create(&phaseOne)
		DB.Create(&phaseTwo)
		DB.Create(&phaseThree)
		DB.Create(&phaseFour)
		DB.Create(&phaseFive)
		DB.Save(&phaseOne)
		DB.Save(&phaseTwo)
		DB.Save(&phaseThree)
		DB.Save(&phaseFour)
		DB.Save(&phaseFive)
		phaseTwo.FirstID = &phaseOne.ID
		phaseThree.FirstID = &phaseOne.ID
		phaseFour.FirstID = &phaseOne.ID
		phaseFive.FirstID = &phaseOne.ID
		phaseOne.NextID = &phaseTwo.ID
		phaseTwo.NextID = &phaseThree.ID
		phaseThree.NextID = &phaseFour.ID
		phaseFour.NextID = &phaseFive.ID
		DB.Save(&phaseOne)
		DB.Save(&phaseTwo)
		DB.Save(&phaseThree)
		DB.Save(&phaseFour)
		DB.Save(&phaseFive)

	} else {
		DB.First(&phaseOne, &Phase{First: nil})
	}
	phaseOneID = phaseOne.ID

	var cardDeckCount int64
	if DB.Table("card_decks").Count(&cardDeckCount); cardDeckCount == 0 {
		cardDeck := CardDeck{
			Title:       "Test Stapel",
			Description: "Dieser Stapel wurde als Beispiel erstllt",
			Cards: []Card{
				{
					Front: "Hallo",
					Back:  "Hello",
					Hint:  "Hallo in Englisch",
				},
				{
					Front: "Auf Wiedersehen",
					Back:  "Bye",
					Hint:  "Auf Wiedersehen auf Englisch",
				},
			},
		}
		DB.Create(&cardDeck)

		DB.Save(&cardDeck)
	}
}
