"""Workstream D trigger wiring: gated, best-effort, and inert while projection is disabled."""

import asyncio
from types import SimpleNamespace
from uuid import uuid4

import pytest
from src.domain.workspaces import service as workspace_service
from src.workers.tasks import project_membership_projection as tasks


def _settings(enabled):
    return SimpleNamespace(project_membership_projection_enabled=enabled)


def test_hook_is_inert_when_projection_disabled(monkeypatch):
    calls = []

    async def fake_enqueue(workspace_id):
        calls.append(workspace_id)
        return True

    monkeypatch.setattr("src.config.get_settings", lambda: _settings(False))
    monkeypatch.setattr("src.workers.enqueue.enqueue_reconcile_workspace_projection", fake_enqueue)
    asyncio.run(workspace_service._schedule_membership_projection(uuid4()))
    assert calls == []


def test_hook_enqueues_when_enabled(monkeypatch):
    calls = []

    async def fake_enqueue(workspace_id):
        calls.append(workspace_id)
        return True

    monkeypatch.setattr("src.config.get_settings", lambda: _settings(True))
    monkeypatch.setattr("src.workers.enqueue.enqueue_reconcile_workspace_projection", fake_enqueue)
    ws = uuid4()
    asyncio.run(workspace_service._schedule_membership_projection(ws))
    assert calls == [str(ws)]


def test_failed_enqueue_never_fails_the_request(monkeypatch):
    async def broken_enqueue(workspace_id):
        raise ConnectionError("redis unavailable")

    monkeypatch.setattr("src.config.get_settings", lambda: _settings(True))
    monkeypatch.setattr(
        "src.workers.enqueue.enqueue_reconcile_workspace_projection", broken_enqueue
    )
    asyncio.run(workspace_service._schedule_membership_projection(uuid4()))


@pytest.mark.parametrize("task", [
    lambda ctx: tasks.reconcile_workspace_projection(ctx, str(uuid4())),
    lambda ctx: tasks.reconcile_project_membership(ctx, str(uuid4())),
    lambda ctx: tasks.reconcile_all_project_memberships(ctx),
])
def test_worker_tasks_are_inert_when_disabled(monkeypatch, task):
    monkeypatch.setattr(tasks, "get_settings", lambda: _settings(False))
    result = asyncio.run(task({}))
    assert result == {"skipped": "projection_disabled"}
