package migrations

import (
	"github.com/uptrace/bun"
	"github.com/uptrace/bun/dialect/feature"
	"github.com/uptrace/bun/migrate"
	"github.com/uptrace/bun/schema"
)

var migrations = migrate.NewMigrations()

func NewMigrator(db *bun.DB, opts ...migrate.MigratorOption) *migrate.Migrator {
	// db isn't required in all cases (e.g. for creating migrations)
	if db != nil {
		db = db.WithNamedArg("ID_COL", autoincrementIDColumn(db))
	}
	return migrate.NewMigrator(db, migrations, opts...)
}

type hasFeaturer interface {
	HasFeature(feat feature.Feature) bool
}

func autoincrementIDColumn(f hasFeaturer) schema.QueryAppender {
	if f.HasFeature(feature.GeneratedIdentity) {
		// postgres
		return bun.Safe("id bigint GENERATED BY DEFAULT AS IDENTITY primary key")
	}

	// sqlite
	return bun.Safe("id INTEGER PRIMARY KEY")
}
