"""Tests for the fire-and-forget background dispatch helper."""

import threading

import pytest

from apps.core.background import run_in_background


class TestEagerMode:
    @pytest.fixture(autouse=True)
    def eager(self, settings):
        settings.BACKGROUND_TASKS_EAGER = True

    def test_runs_inline(self):
        calls = []
        run_in_background(calls.append, "ran")
        assert calls == ["ran"]

    def test_swallows_exceptions(self):
        def boom():
            raise RuntimeError("nope")
        run_in_background(boom)  # must not raise

    def test_passes_kwargs(self):
        calls = {}
        run_in_background(calls.update, key="value")
        assert calls == {"key": "value"}


class TestThreadedMode:
    @pytest.mark.django_db
    def test_runs_on_background_thread(self):
        done = threading.Event()
        seen = {}

        def task(value):
            seen["value"] = value
            seen["thread"] = threading.current_thread().name
            done.set()

        run_in_background(task, 42)
        assert done.wait(timeout=5), "background task never ran"
        assert seen["value"] == 42
        assert seen["thread"].startswith("khub-bg")

    @pytest.mark.django_db
    def test_exception_does_not_propagate(self):
        done = threading.Event()

        def boom():
            done.set()
            raise RuntimeError("nope")

        run_in_background(boom)
        assert done.wait(timeout=5)
