package comm

import (
	"fmt"
	"os"
	"strings"

	"github.com/golang-migrate/migrate/v4"
	"github.com/golang-migrate/migrate/v4/database/mongodb"
	_ "github.com/golang-migrate/migrate/v4/source/file"
)

func AppMongoMiration() {

	///data/migrations==mongodb://root:3dshow@3dshow-mongo-alpha:27017/dbname?query&&/data/migrations==mongodb://user:password@host:port/dbname?query
	config := os.Getenv("MONGO_MIGRATIONS")
	if len(config) < 1 {
		return
	}

	dbs := strings.Split(config, "&&")
	fmt.Println("mongo_migrations_dbs: ", dbs)

	for _, db := range dbs {

		frags := strings.Split(db, "==")
		if len(frags) != 2 {
			panic("mongo-migration config err=>" + db)
		}

		sourc := frags[0]
		dbUri := frags[1]
		p := &mongodb.Mongo{}
		d, err := p.Open(dbUri)
		if err != nil {
			panic("mongo-migration open err=>" + err.Error())
		}
		fileSource := fmt.Sprintf("file://%s", sourc)
		fmt.Println("mongo_migrations_file_source: ", fileSource)
		mi, err := migrate.NewWithDatabaseInstance(fileSource, "", d)
		if err != nil {
			panic("mongo-migration new instance err=>" + err.Error())
		}
		err = mi.Up()
		if err != nil {
			fmt.Println("mongo-migration up err=>" + err.Error())
		}

	}
}
