from __future__ import annotations

from collections.abc import Iterator
from contextlib import contextmanager

from govoplan_core.db.session import DatabaseHandle, configure_database, get_database, reset_database, set_database


@contextmanager
def temporary_database(database_url: str) -> Iterator[DatabaseHandle]:
    try:
        previous_database = get_database()
    except RuntimeError:
        previous_database = None

    database = configure_database(database_url)
    should_dispose = database is not previous_database
    try:
        yield database
    finally:
        if should_dispose:
            database.engine.dispose()
        if previous_database is None:
            reset_database()
        else:
            set_database(previous_database)
