package store

import (
	"database/sql"
	"errors"
	"fmt"
	"io/fs"

	"github.com/golang-migrate/migrate/v4"
	migratedb "github.com/golang-migrate/migrate/v4/database"
	migratemysql "github.com/golang-migrate/migrate/v4/database/mysql"
	migratesqlite "github.com/golang-migrate/migrate/v4/database/sqlite"
	"github.com/golang-migrate/migrate/v4/source/iofs"

	"github.com/wangjia/pangolin/server/internal/db"
	"github.com/wangjia/pangolin/server/migrations"
)

// MigrateUp runs all pending up migrations for the given driver
// ("mysql" | "sqlite"). migrate.ErrNoChange is treated as success (idempotent).
func MigrateUp(database *sql.DB, driver string) error {
	return runMigration(database, driver, func(m *migrate.Migrate) error {
		return m.Up()
	})
}

// MigrateDown rolls back all applied migrations. ErrNoChange = success.
func MigrateDown(database *sql.DB, driver string) error {
	return runMigration(database, driver, func(m *migrate.Migrate) error {
		return m.Down()
	})
}

// MigrateVersion returns the currently applied migration version and whether
// the schema is in a dirty state. Returns version 0 and no error when no
// migrations have been applied yet.
func MigrateVersion(database *sql.DB, driver string) (uint, bool, error) {
	m, cleanup, err := newMigrator(database, driver)
	if err != nil {
		return 0, false, err
	}
	defer cleanup()

	v, dirty, err := m.Version()
	if errors.Is(err, migrate.ErrNilVersion) {
		return 0, false, nil
	}
	if err != nil {
		return 0, false, fmt.Errorf("store.migrate: version: %w", err)
	}
	return v, dirty, nil
}

// runMigration opens a migrator, calls fn, and handles ErrNoChange.
func runMigration(database *sql.DB, driver string, fn func(*migrate.Migrate) error) error {
	m, cleanup, err := newMigrator(database, driver)
	if err != nil {
		return err
	}
	defer cleanup()

	if err := fn(m); err != nil && !errors.Is(err, migrate.ErrNoChange) {
		return fmt.Errorf("store.migrate: %w", err)
	}
	return nil
}

// newMigrator creates a golang-migrate instance backed by the embedded SQL
// files for the chosen dialect and the provided *sql.DB. The caller must invoke
// cleanup() to release source and driver resources.
func newMigrator(database *sql.DB, driver string) (*migrate.Migrate, func(), error) {
	embedFS, sub, dbName := migrationSource(driver)

	src, err := iofs.New(embedFS, sub)
	if err != nil {
		return nil, nil, fmt.Errorf("store.migrate: iofs source: %w", err)
	}

	mdriver, err := newMigrateDriver(driver, database)
	if err != nil {
		_ = src.Close()
		return nil, nil, fmt.Errorf("store.migrate: %s driver: %w", dbName, err)
	}

	m, err := migrate.NewWithInstance("iofs", src, dbName, mdriver)
	if err != nil {
		_ = src.Close()
		_ = mdriver.Close()
		return nil, nil, fmt.Errorf("store.migrate: new migrator: %w", err)
	}

	// Close only the embedded source, NOT the database driver: m.Close() would
	// close the caller-owned *sql.DB (the WithInstance driver closes the handle
	// it was given — fatal for a shared/in-memory connection the caller reuses).
	// The caller owns the *sql.DB and closes it when done.
	cleanup := func() {
		_ = src.Close()
	}
	return m, cleanup, nil
}

// migrationSource returns the embedded FS, its subdir, and the golang-migrate
// database name for the given driver.
func migrationSource(driver string) (fs.FS, string, string) {
	if db.Normalize(driver) == "sqlite" {
		return migrations.SQLiteFS, "sqlite", "sqlite"
	}
	return migrations.MySQLFS, "mysql", "mysql"
}

// newMigrateDriver builds the golang-migrate database driver for the dialect.
func newMigrateDriver(driver string, database *sql.DB) (migratedb.Driver, error) {
	if db.Normalize(driver) == "sqlite" {
		return migratesqlite.WithInstance(database, &migratesqlite.Config{})
	}
	return migratemysql.WithInstance(database, &migratemysql.Config{})
}
