"""Tests for the shared background task database helper."""

from __future__ import annotations

from unittest.mock import AsyncMock, patch

import pytest

from app.tasks.db import task_db


class FakeSettings:
    database_path = "/tmp/fake.db"


@pytest.mark.asyncio
async def test_task_db_opens_and_closes_connection() -> None:
    """``task_db`` must open a DB connection and close it after use."""
    fake_db = AsyncMock()
    fake_db.close = AsyncMock()

    with patch("app.tasks.db.open_db", new_callable=AsyncMock, return_value=fake_db) as mock_open_db:
        async with task_db(FakeSettings()) as db:
            assert db is fake_db

    mock_open_db.assert_awaited_once_with("/tmp/fake.db")
    fake_db.close.assert_awaited_once()


@pytest.mark.asyncio
async def test_task_db_closes_connection_on_exception() -> None:
    """``task_db`` must close the connection even when the body raises."""
    fake_db = AsyncMock()
    fake_db.close = AsyncMock()

    with patch(
        "app.tasks.db.open_db",
        new_callable=AsyncMock,
        return_value=fake_db,
    ), pytest.raises(RuntimeError, match="boom"):
        async with task_db(FakeSettings()):
            raise RuntimeError("boom")

    fake_db.close.assert_awaited_once()
