package main

import (
	"flag"
	"fmt"
	"log"
	"os"

	"github.com/go-pg/migrations/v8"
	"github.com/go-pg/pg/v10"

	"git.ego.freeddns.org/egommerce/go-api-pkg/fluentd"

	baseCnf "git.ego.freeddns.org/egommerce/go-api-pkg/config"
	cnf "git.ego.freeddns.org/egommerce/identity-service/internal/server"
)

const (
	defMigrationsTableName = "identity.migrations"
)

const usageText = `This program runs command on the db. Supported commands are:
  - init - creates version info table in the database
  - up - runs all available migrations.
  - up [target] - runs available migrations up to the target one.
  - down - reverts last migration.
  - reset - reverts all migrations.
  - version - prints current db version.
  - set_version [version] - sets db version without running migrations.
Usage:
  go run cmd/migrate/main.go <command> [args]
`

func main() {
	flag.Usage = func() {
		fmt.Print(usageText)
		flag.PrintDefaults()
		os.Exit(2)
	}
	flag.Parse()

	if baseCnf.ErrLoadingEnvs != nil {
		log.Panicln(baseCnf.ErrLoadingEnvs)
	}

	c := cnf.NewConfig("migrator")

	// dbURL := baseCnf.GetEnv("DATABASE_URL", defDbURL)

	logHost, logPort, err := fluentd.ParseAddr(c.LoggerAddr)
	if err != nil {
		log.Fatalf("Error parsing logger addr: %s. Err: %v", c.LoggerAddr, err)
	}

	logger, err := fluentd.NewLogger(c.GetAppFullName(), logHost, logPort) // @Refactor NewLogger return (logger, error)
	if err != nil {
		log.Fatalf("Error connecting to %s:%d. Err: %v", logHost, logPort, err)
	}
	defer logger.Close()

	db := pg.Connect(&pg.Options{ // FIXME
		Addr:     "db:5432",
		User:     "egommerce",
		Password: "12345678",
		Database: "egommerce",
	})
	defer db.Close()

	mTbl := baseCnf.GetEnv("MIGRATIONS_TABLE_NAME", defMigrationsTableName)
	mig := migrations.NewCollection()
	mig.SetTableName(mTbl)
	if err := mig.DiscoverSQLMigrations("./migrations"); err != nil {
		logger.Log("migration dicovery error: %#v", err)
	}

	oldVersion, newVersion, err := mig.Run(db, flag.Args()...)
	if err != nil {
		logger.Log("migration runner error: %#v", err)
		os.Exit(1)
	}
	if newVersion != oldVersion {
		logger.Log("migrated from version %d to %d\n", oldVersion, newVersion)
	} else {
		logger.Log("version is %d\n", oldVersion)
	}
	// os.Exit(0)
}
