/*
model-gen generates the gorm-gen interface for interacting
with the database. It does not perform migrations on the database.
*/
package main

import (
	"flag"

	"git.mstar.dev/mstar/goutils/other"
	"github.com/rs/zerolog/log"
	"gorm.io/driver/postgres"
	"gorm.io/gen"
	"gorm.io/gorm"

	"git.mstar.dev/mstar/linstrom/config"
	"git.mstar.dev/mstar/linstrom/shared"
	"git.mstar.dev/mstar/linstrom/storage-new/models"
)

func main() {
	flagOutPath := flag.String("outpath", "./dbgen", "Set the path to generate to")
	other.SetupFlags()
	flag.Parse()
	other.ConfigureLogging(nil)
	config.ReadAndWriteToGlobal(*shared.FlagConfigFile)

	db, err := gorm.Open(
		postgres.Open(config.GlobalConfig.Storage.BuildPostgresDSN()),
		&gorm.Config{
			PrepareStmt: false,
			Logger:      shared.NewGormLogger(log.Logger),
		},
	)
	if err != nil {
		log.Fatal().Err(err).Msg("Failed to open connection to temporary container")
	}
	log.Info().Msg("Connected to db")
	g := gen.NewGenerator(gen.Config{
		OutPath: *flagOutPath,
		Mode:    gen.WithoutContext | gen.WithDefaultQuery | gen.WithQueryInterface, // generate mode
	})
	g.UseDB(db)

	log.Info().Msg("Applying basic operations on all datatypes")
	g.ApplyBasic(models.AllTypes...)

	log.Info().Msg("Basic operations applied, applying extra features")
	g.ApplyInterface(func(models.INotification) {}, models.Notification{})
	g.ApplyInterface(func(models.IUser) {}, models.User{})
	g.ApplyInterface(func(models.IAccessToken) {}, models.AccessToken{})

	log.Info().Msg("Extra features applied, starting generation")
	g.Execute()
	log.Info().Msg("Code generation complete")
}
