from __future__ import annotations

import unittest
from unittest.mock import patch

from govoplan_core.commands.wait_for_database import main


class WaitForDatabaseTests(unittest.TestCase):
    def test_waits_until_exact_configured_heads_are_visible(self) -> None:
        with (
            patch(
                "govoplan_core.commands.wait_for_database.configured_migration_heads",
                return_value=("head-a", "head-b"),
            ),
            patch(
                "govoplan_core.commands.wait_for_database.database_migration_heads",
                side_effect=[("head-a",), ("head-a", "head-b")],
            ),
            patch("govoplan_core.commands.wait_for_database.time.sleep"),
        ):
            result = main(["--timeout-seconds", "1", "--poll-seconds", "0.01"])

        self.assertEqual(0, result)

    def test_returns_temporary_failure_when_heads_do_not_match(self) -> None:
        with (
            patch(
                "govoplan_core.commands.wait_for_database.configured_migration_heads",
                return_value=("head-b",),
            ),
            patch(
                "govoplan_core.commands.wait_for_database.database_migration_heads",
                return_value=("head-a",),
            ),
        ):
            result = main(["--timeout-seconds", "0"])

        self.assertEqual(75, result)


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