from __future__ import annotations

from pathlib import Path
import sys
import unittest


SRC_ROOT = Path(__file__).resolve().parents[2] / "src"

if str(SRC_ROOT) not in sys.path:
    sys.path.insert(0, str(SRC_ROOT))


from ffx.model.migration import (  # noqa: E402
    DatabaseVersionException,
    getMigrationPlan,
    loadMigrationStep,
    migrateDatabase,
)


class MigrationTests(unittest.TestCase):
    def test_get_migration_plan_lists_known_step_with_module_presence(self):
        migrationPlan = getMigrationPlan(2, 3)

        self.assertEqual(1, len(migrationPlan))
        self.assertEqual(2, migrationPlan[0].versionFrom)
        self.assertEqual(3, migrationPlan[0].versionTo)
        self.assertEqual("ffx.model.migration.step_2_3", migrationPlan[0].moduleName)
        self.assertTrue(migrationPlan[0].modulePresent)

    def test_load_migration_step_returns_known_step(self):
        migrationStep = loadMigrationStep(2, 3)

        self.assertTrue(callable(migrationStep))

    def test_migrate_database_raises_when_step_module_is_missing(self):
        updatedVersions = []

        with self.assertRaises(DatabaseVersionException):
            migrateDatabase({}, 1, 2, lambda context, version: updatedVersions.append(version))

        self.assertEqual([], updatedVersions)


if __name__ == "__main__":
    unittest.main()
