package migrator

import (
	"database/sql"
	"fmt"

	"git.gocasts.ir/ebhomengo/niki/pkg/database/mysql"
	migrate "github.com/rubenv/sql-migrate"
)

type Config struct {
	MysqlConfig     mysql.Config
	MigrationPath   string
	MigrationDBName string
}

type Migrator struct {
	cfg        Config
	dialect    string
	migrations *migrate.FileMigrationSource
}

// TODO - set migration table name
// TODO - add limit to Up and Down method

func New(cfg Config) Migrator {
	// OR: Read migrations from a folder:
	migrations := &migrate.FileMigrationSource{
		Dir: cfg.MigrationPath,
	}

	return Migrator{cfg: cfg, dialect: "mysql", migrations: migrations}
}

func (m Migrator) Up() {
	migrate.SetTable(m.cfg.MigrationDBName)

	db, err := sql.Open(m.dialect, fmt.Sprintf("%s:%s@(%s:%d)/%s?parseTime=true",
		m.cfg.MysqlConfig.Username, m.cfg.MysqlConfig.Password, m.cfg.MysqlConfig.Host, m.cfg.MysqlConfig.Port, m.cfg.MysqlConfig.DBName))
	if err != nil {
		panic(fmt.Errorf("can't open mysql db: %w", err))
	}

	n, err := migrate.Exec(db, m.dialect, m.migrations, migrate.Up)
	if err != nil {
		panic(fmt.Errorf("can't apply migrations: %w", err))
	}
	fmt.Printf("Applied %d migrations!\n", n)
}

func (m Migrator) Down() {
	migrate.SetTable(m.cfg.MigrationDBName)

	db, err := sql.Open(m.dialect, fmt.Sprintf("%s:%s@(%s:%d)/%s?parseTime=true",
		m.cfg.MysqlConfig.Username, m.cfg.MysqlConfig.Password, m.cfg.MysqlConfig.Host, m.cfg.MysqlConfig.Port, m.cfg.MysqlConfig.DBName))
	if err != nil {
		panic(fmt.Errorf("can't open mysql db: %w", err))
	}

	n, err := migrate.Exec(db, m.dialect, m.migrations, migrate.Down)
	if err != nil {
		panic(fmt.Errorf("can't rollback migrations: %w", err))
	}
	fmt.Printf("Rollbacked %d migrations!\n", n)
}

func (m Migrator) Status() {
	// TODO - add status
}
