"""
Unit tests for:
  - POST  /hr-assist-stream       (SSE streaming endpoint)
  - GET   /conversations          (list conversations by JWT company_id)
  - DELETE /conversations/{id}    (soft-delete a conversation)

All external dependencies (PostgreSQL, Redis, LangGraph, LLM calls) are mocked.
No real server, database, or network connection is needed to run these tests.
"""

import json
import pytest
from contextlib import ExitStack
from unittest.mock import MagicMock, patch

import main
from main import app
from dependencies import enforce_token_quota
from tests.conftest import (
    TEST_COMPANY_ID,
    TEST_CONV_ID,
    FAKE_CONVERSATION,
)


# ─────────────────────────────────────────────────────────────────────────────
# Helpers
# ─────────────────────────────────────────────────────────────────────────────

async def collect_stream(client, json_body: dict) -> list[dict]:
    """POST to /hr-assist-stream and collect all SSE events as parsed dicts."""
    events = []
    async with client.stream("POST", "/hr-assist-stream", json=json_body) as resp:
        async for line in resp.aiter_lines():
            if line.startswith("data: "):
                try:
                    events.append(json.loads(line[6:]))
                except json.JSONDecodeError:
                    pass
    return events


# ─────────────────────────────────────────────────────────────────────────────
# Async mock for _get_server_ip
# Using a plain async function avoids the "coroutine never awaited" warning
# that AsyncMock triggers when stopped inside a .start()/.stop() pattern.
# ─────────────────────────────────────────────────────────────────────────────

async def _mock_server_ip():
    return "1.2.3.4"


# ─────────────────────────────────────────────────────────────────────────────
# Mock LangGraph async generators
# ─────────────────────────────────────────────────────────────────────────────

async def _hr_astream(state, stream_mode=None):
    """Simulates a successful HR-query run through the LangGraph pipeline."""
    yield {"type": "guardrail", "stage": "input", "status": "skipped"}
    yield {"type": "intent", "intent": "leave_policy", "is_hr": True}
    yield {"type": "guardrail", "stage": "output", "status": "skipped"}
    yield {"type": "chunk", "content": "Annual leave is 20 working days per year."}
    yield {
        "type": "done",
        "intent": "leave_policy",
        "is_hr": True,
        "data": {"answer": "Annual leave is 20 working days per year."},
        "message": "Here is the leave policy information.",
    }


async def _non_hr_astream(state, stream_mode=None):
    """Simulates a non-HR query being redirected."""
    yield {"type": "intent", "intent": "non_hr", "is_hr": False}
    yield {
        "type": "chunk",
        "content": "I'm Helix AI Assistant, specialized exclusively in HR topics.",
    }
    yield {
        "type": "done",
        "intent": "non_hr",
        "is_hr": False,
        "data": {"answer": "I'm Helix AI Assistant, specialized exclusively in HR topics."},
        "message": "I'm Helix AI Assistant, specialized exclusively in HR topics.",
    }


async def _blocked_astream(state, stream_mode=None):
    """Simulates a query blocked by the input guardrail."""
    yield {
        "type": "guardrail",
        "stage": "input",
        "status": "failed",
        "categories": ["hate"],
        "message": "Your message was flagged by safety guardrails.",
    }


# ─────────────────────────────────────────────────────────────────────────────
# Shared stream fixture
#
# Using ExitStack so each test gets fresh MagicMock instances that are
# properly started and stopped.  Individual tests can override a specific
# patch by adding another patch() inside a `with` block — Python's patch
# stacks, so the innermost (last-applied) wins.
# ─────────────────────────────────────────────────────────────────────────────

@pytest.fixture
def stream_mocks():
    """
    Activates all standard patches for /hr-assist-stream tests and yields a
    dict of mock objects keyed by their patch target.  Tests can read or
    assert on these mocks, or override them with an inner `with patch(...)`.
    """
    with ExitStack() as stack:
        mocks = {
            "get_conversation_by_id": stack.enter_context(
                patch("main.get_conversation_by_id", return_value=FAKE_CONVERSATION)
            ),
            "create_conversation": stack.enter_context(
                patch("main.create_conversation", return_value=FAKE_CONVERSATION)
            ),
            "create_conversation_with_id": stack.enter_context(
                patch("main.create_conversation_with_id", return_value=FAKE_CONVERSATION)
            ),
            "add_user_message": stack.enter_context(patch("main.add_user_message")),
            "get_messages": stack.enter_context(
                patch("main.get_messages", return_value=[])
            ),
            "get_context": stack.enter_context(
                patch("main.get_context", return_value=[])
            ),
            "get_cached_query": stack.enter_context(
                patch("main.get_cached_query", return_value=None)
            ),
            "save_message": stack.enter_context(patch("main.save_message")),
            "add_ai_message": stack.enter_context(patch("main.add_ai_message")),
            "set_cached_query": stack.enter_context(patch("main.set_cached_query")),
            "store_hr_log": stack.enter_context(patch("main.store_hr_log")),
            "server_ip": stack.enter_context(
                patch("main._get_server_ip", new=_mock_server_ip)
            ),
        }
        yield mocks


# ═════════════════════════════════════════════════════════════════════════════
# POST /hr-assist-stream
# ═════════════════════════════════════════════════════════════════════════════

class TestHrAssistStream:

    # ── Happy path: existing conversation ────────────────────────────────────

    async def test_stream_existing_conversation_returns_events_in_order(
        self, client, stream_mocks
    ):
        """
        Full happy path: conversation_id provided → events arrive in the
        expected order and contain the correct conversation_id and server_ip.
        """
        with patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            events = await collect_stream(client, {
                "query": "What is the annual leave policy?",
                "conversation_id": TEST_CONV_ID,
            })

        types = [e["type"] for e in events]
        assert "intent" in types
        assert "chunk" in types
        assert "done" in types

        intent_event = next(e for e in events if e["type"] == "intent")
        assert intent_event["intent"] == "leave_policy"
        assert intent_event["is_hr"] is True
        assert intent_event["conversation_id"] == TEST_CONV_ID

        done_event = next(e for e in events if e["type"] == "done")
        assert done_event["conversation_id"] == TEST_CONV_ID
        assert done_event["cached"] is False
        assert done_event["server_ip"] == "1.2.3.4"

        chunk_text = "".join(
            e["content"] for e in events if e["type"] == "chunk"
        )
        assert "Annual leave" in chunk_text

    # ── Happy path: new conversation created ─────────────────────────────────

    async def test_stream_no_conversation_id_creates_new(
        self, client, stream_mocks
    ):
        """
        When conversation_id is omitted the endpoint creates a new conversation
        and the done event carries the generated conversation_id.
        """
        with patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            events = await collect_stream(client, {
                "query": "What is the payroll cycle?",
            })

        done_event = next((e for e in events if e["type"] == "done"), None)
        assert done_event is not None
        assert done_event.get("conversation_id") == TEST_CONV_ID

    # ── Continuity: unrecognized client-generated conversation_id gets adopted ──

    async def test_stream_unrecognized_conversation_id_gets_adopted(
        self, client, stream_mocks
    ):
        """
        The Angular client always pre-generates its own conversation_id and
        sends it on every request, including the very first one for a brand
        new chat. If get_conversation_by_id doesn't find it under the
        caller's company_id (nothing has been persisted under it yet), the
        endpoint must ADOPT it — create the row using that exact id — so the
        conversation the client thinks it's in is the conversation that
        actually gets built up turn over turn. Regression test for a bug
        where this case always minted a fresh, different server-side id
        instead, silently resetting conversation state (including in-progress
        apply-leave slot-filling) on every single turn.
        """
        client_generated_id = "conv_1700000000000_abc123xyz9"

        with patch("main.get_conversation_by_id", return_value=None), \
             patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            events = await collect_stream(client, {
                "query": "What is the annual leave policy?",
                "conversation_id": client_generated_id,
            })

        done_event = next((e for e in events if e["type"] == "done"), None)
        assert done_event is not None
        assert done_event["conversation_id"] == client_generated_id

    # ── IDOR guard: a genuine id collision still falls back to a fresh id ──

    async def test_stream_conversation_id_collision_falls_back_to_fresh_id(
        self, client, stream_mocks
    ):
        """
        If the supplied conversation_id isn't found under the caller's
        company_id (get_conversation_by_id returns None) but adoption fails
        because that exact id string already exists as a row — which,
        having already missed the caller's own company-scoped lookup, can
        only mean it belongs to another company — create_conversation_with_id
        returns None on the resulting primary-key collision. The endpoint
        must then fall back to minting a brand-new conversation with a fresh
        server-assigned id, exactly like the no-conversation_id path — never
        adopting or exposing another company's conversation.
        """
        from types import SimpleNamespace
        other_companys_conv_id = "someone-elses-conv-id"
        fresh_conversation = SimpleNamespace(id="fresh-server-generated-id")

        with patch("main.get_conversation_by_id", return_value=None), \
             patch("main.create_conversation_with_id", return_value=None), \
             patch("main.create_conversation", return_value=fresh_conversation), \
             patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            events = await collect_stream(client, {
                "query": "What is the annual leave policy?",
                "conversation_id": other_companys_conv_id,
            })

        done_event = next((e for e in events if e["type"] == "done"), None)
        assert done_event is not None
        assert done_event["conversation_id"] == "fresh-server-generated-id"
        assert done_event["conversation_id"] != other_companys_conv_id

    # ── Cache hit ─────────────────────────────────────────────────────────────

    async def test_stream_cache_hit_returns_cached_events(
        self, client, stream_mocks
    ):
        """
        When a matching entry exists in Redis query cache the endpoint streams
        the cached answer immediately (no LangGraph call) with cached=True.

        The inner `with patch(...)` overrides the fixture's get_cached_query
        mock — Python's patch stacks; the innermost value wins.
        """
        cached_payload = {
            "success": True,
            "intent": "leave_policy",
            "result": "You get 20 days of annual leave.",
        }

        with patch("main.get_cached_query", return_value=cached_payload):
            events = await collect_stream(client, {
                "query": "What is the annual leave policy?",
                "conversation_id": TEST_CONV_ID,
            })

        types = [e["type"] for e in events]
        assert "intent" in types
        assert "chunk" in types
        assert "done" in types

        done_event = next(e for e in events if e["type"] == "done")
        assert done_event["cached"] is True
        assert done_event["intent"] == "leave_policy"

        chunk_event = next(e for e in events if e["type"] == "chunk")
        assert "20 days" in chunk_event["content"]

    async def test_stream_cache_hit_ignored_for_stateful_leave_intent(
        self, client, stream_mocks
    ):
        """
        Regression: a cached "apply_leave"/"leave_balance"/"leave_status"
        answer must NEVER be replayed — leave_action_node's Redis slot state
        is a real side effect a cache replay skips entirely, so a second
        conversation asking the exact same phrase would get a response
        implying slots were captured when none actually were, breaking the
        very next turn. The endpoint must fall through to a real graph run.
        """
        cached_payload = {
            "success": True,
            "intent": "apply_leave",
            "result": "Would that be a full day or half day?",
        }

        async def _apply_leave_astream(state, stream_mode=None):
            yield {"type": "intent", "intent": "apply_leave", "is_hr": True}
            yield {
                "type": "done", "intent": "apply_leave", "is_hr": True,
                "data": {"answer": "What type of leave would you like to apply for?"},
                "message": "What type of leave would you like to apply for?",
            }

        with patch("main.get_cached_query", return_value=cached_payload), \
             patch.object(main.hr_graph, "astream", side_effect=_apply_leave_astream):
            events = await collect_stream(client, {
                "query": "Apply casual leave tomorrow.",
            })

        done_event = next(e for e in events if e["type"] == "done")
        # Real graph ran — NOT the stale cached answer, and cached must be False.
        assert done_event["cached"] is False
        assert done_event["data"]["answer"] == "What type of leave would you like to apply for?"

    # ── Non-HR redirect ───────────────────────────────────────────────────────

    async def test_stream_non_hr_query_sends_redirect_message(
        self, client, stream_mocks
    ):
        """
        Queries outside HR scope are classified as non_hr and the pipeline
        streams a redirect message instead of an LLM-generated answer.
        """
        with patch.object(main.hr_graph, "astream", side_effect=_non_hr_astream):
            events = await collect_stream(client, {
                "query": "What is the weather today?",
                "conversation_id": TEST_CONV_ID,
            })

        intent_event = next((e for e in events if e["type"] == "intent"), None)
        assert intent_event is not None
        assert intent_event["intent"] == "non_hr"
        assert intent_event["is_hr"] is False

        chunk_event = next((e for e in events if e["type"] == "chunk"), None)
        assert chunk_event is not None
        assert "HR" in chunk_event["content"] or "Helix" in chunk_event["content"]

    # ── Guardrail blocked ─────────────────────────────────────────────────────

    async def test_stream_guardrail_blocked_sends_failed_event(
        self, client, stream_mocks
    ):
        """
        When the input guardrail flags the query a guardrail-failed event is
        streamed and no chunk or done events follow.
        """
        with patch.object(main.hr_graph, "astream", side_effect=_blocked_astream):
            events = await collect_stream(client, {
                "query": "Harmful query content",
                "conversation_id": TEST_CONV_ID,
            })

        failed = next(
            (e for e in events if e["type"] == "guardrail" and e.get("status") == "failed"),
            None,
        )
        assert failed is not None
        assert failed["stage"] == "input"
        assert "hate" in failed["categories"]
        assert not any(e["type"] == "chunk" for e in events)

    # ── Missing query field ───────────────────────────────────────────────────

    async def test_stream_missing_query_returns_400(self, client):
        """Body without 'query' key must return HTTP 400."""
        response = await client.post(
            "/hr-assist-stream",
            json={"conversation_id": TEST_CONV_ID},
        )
        assert response.status_code == 400
        assert "Query required" in response.json()["detail"]

    # ── No Authorization header ───────────────────────────────────────────────

    async def test_stream_no_auth_header_returns_401_or_422(self, unauth_client):
        """Request without Authorization header must be rejected."""
        response = await unauth_client.post(
            "/hr-assist-stream",
            json={"query": "What is leave policy?"},
        )
        assert response.status_code in (401, 422)

    # ── Invalid JWT token ─────────────────────────────────────────────────────

    async def test_stream_invalid_jwt_returns_401(self, unauth_client):
        """A request with a malformed token must return HTTP 401."""
        response = await unauth_client.post(
            "/hr-assist-stream",
            headers={"Authorization": "Bearer this.is.not.a.valid.jwt"},
            json={"query": "What is leave policy?"},
        )
        assert response.status_code == 401

    # ── Redis AI message write after stream ───────────────────────────────────

    async def test_stream_writes_ai_message_to_redis_after_done(
        self, client, stream_mocks
    ):
        """
        After a successful stream the finally block must call add_ai_message
        to persist the assistant reply into Redis chat history.

        We override the fixture's add_ai_message with a spy, then assert it
        was called once with the correct company_id, conversation_id, and text.
        """
        spy = MagicMock()

        with patch("main.add_ai_message", spy), \
             patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            await collect_stream(client, {
                "query": "What is annual leave?",
                "conversation_id": TEST_CONV_ID,
            })

        spy.assert_called_once()
        args = spy.call_args[0]
        assert args[0] == TEST_COMPANY_ID       # company_id
        assert args[1] == TEST_CONV_ID           # conversation_id
        assert "Annual leave" in args[2]         # full answer text

    # ── Query cache populated for fresh queries ───────────────────────────────

    async def test_stream_populates_query_cache_for_fresh_query(
        self, client, stream_mocks
    ):
        """
        When a query has no prior context (is_fresh_query=True) the finally
        block must call set_cached_query so future identical queries are served
        from cache. Also asserts the cache write is scoped by company_id
        (IDOR/cross-tenant-leak regression — see test_stream_cache_read_scoped_by_company_id).
        """
        spy = MagicMock()

        with patch("main.set_cached_query", spy), \
             patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            await collect_stream(client, {
                "query": "What is annual leave?",
                "conversation_id": TEST_CONV_ID,
            })

        spy.assert_called_once()
        _, called_company_id, cache_payload = spy.call_args[0]
        assert called_company_id == TEST_COMPANY_ID
        assert cache_payload["success"] is True
        assert cache_payload["intent"] == "leave_policy"
        assert "Annual leave" in cache_payload["result"]

    # ── Query cache read scoped by company (IDOR regression) ───────────────────

    async def test_stream_cache_read_scoped_by_company_id(
        self, client, stream_mocks
    ):
        """
        get_cached_query must be called with the caller's company_id, not just
        the raw query text — otherwise one company's cached AI answer could be
        served to a different company asking an identically-normalized
        question (cross-tenant leak, same class of bug as the earlier
        conversation IDOR fix).
        """
        spy = MagicMock(return_value=None)

        with patch("main.get_cached_query", spy), \
             patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            await collect_stream(client, {
                "query": "What is annual leave?",
                "conversation_id": TEST_CONV_ID,
            })

        spy.assert_called_once()
        called_query, called_company_id = spy.call_args[0]
        assert called_query == "What is annual leave?"
        assert called_company_id == TEST_COMPANY_ID


# ═════════════════════════════════════════════════════════════════════════════
# Redis Failure Tests
#
# Every Redis call in /hr-assist-stream is wrapped in try/except or
# asyncio.wait_for(..., timeout=1).  These tests confirm the system degrades
# gracefully — the client always gets a valid response regardless of Redis state.
#
# Failure paths tested:
#   1. add_user_message raises          → warning logged, stream continues
#   2. get_messages raises              → caught, falls back to DB (get_context)
#   3. get_messages returns []          → DB fallback triggered (get_context called)
#   4. get_cached_query raises          → caught, treated as cache miss
#   5. add_ai_message raises (finally)  → caught, DB save still executed
#   6. set_cached_query raises (finally)→ caught, response still returned
#   7. Full outage (all ops fail)       → DB fallback used, full LLM response served
#   8. Redis down, DB save still works  → save_message called regardless of Redis
# ═════════════════════════════════════════════════════════════════════════════

class TestRedisFailure:

    # ── 1. add_user_message raises ────────────────────────────────────────────

    async def test_redis_write_failure_does_not_crash_stream(
        self, client, stream_mocks
    ):
        """
        When add_user_message raises (Redis unreachable) the exception is caught
        and logged as a warning.  The stream must continue and deliver a complete
        response to the client.
        """
        with patch("main.add_user_message", side_effect=Exception("Redis connection refused")), \
             patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            events = await collect_stream(client, {
                "query": "What is the leave policy?",
                "conversation_id": TEST_CONV_ID,
            })

        # Full response delivered despite Redis write failure
        assert any(e["type"] == "done" for e in events)
        chunk_text = "".join(e["content"] for e in events if e["type"] == "chunk")
        assert "Annual leave" in chunk_text

    # ── 2. get_messages raises → DB fallback ──────────────────────────────────

    async def test_redis_read_failure_falls_back_to_db_context(
        self, client, stream_mocks
    ):
        """
        When get_messages raises (Redis unavailable) the exception is caught,
        context_messages is set to [], and get_context (PostgreSQL) is called
        as the fallback.  The stream must still complete successfully.
        """
        from types import SimpleNamespace
        db_message = SimpleNamespace(role="user", content="previous question from DB")
        spy_get_context = MagicMock(return_value=[db_message])

        with patch("main.get_messages", side_effect=Exception("Redis timeout")), \
             patch("main.get_context", spy_get_context), \
             patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            events = await collect_stream(client, {
                "query": "What is the leave policy?",
                "conversation_id": TEST_CONV_ID,
            })

        # DB was queried as the fallback source of context
        spy_get_context.assert_called_once()
        # Stream still delivered a full response
        assert any(e["type"] == "done" for e in events)

    # ── 3. get_messages returns [] → DB fallback still triggered ──────────────

    async def test_redis_empty_triggers_db_context_fallback(
        self, client, stream_mocks
    ):
        """
        When Redis returns an empty list (cache cold / key expired) the endpoint
        must fall back to PostgreSQL for conversation context via get_context.
        No exception is raised — this is normal degradation when Redis is empty.
        """
        spy_get_context = MagicMock(return_value=[])

        # stream_mocks already has get_messages returning [] — just spy on get_context
        with patch("main.get_context", spy_get_context), \
             patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            events = await collect_stream(client, {
                "query": "What is the leave policy?",
                "conversation_id": TEST_CONV_ID,
            })

        # get_context must be called because Redis returned nothing
        spy_get_context.assert_called_once()
        assert any(e["type"] == "done" for e in events)

    # ── 4. get_cached_query raises → treated as cache miss ────────────────────

    async def test_redis_cache_read_failure_treated_as_miss(
        self, client, stream_mocks
    ):
        """
        When get_cached_query raises (Redis error during cache lookup) the
        exception is caught and the request proceeds as if no cache entry
        exists — LangGraph is called and a fresh LLM response is served.
        The done event must have cached=false.
        """
        with patch("main.get_cached_query", side_effect=Exception("Cache read error")), \
             patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            events = await collect_stream(client, {
                "query": "What is the leave policy?",
                "conversation_id": TEST_CONV_ID,
            })

        # LangGraph ran → intent event present
        assert any(e["type"] == "intent" for e in events)
        done = next((e for e in events if e["type"] == "done"), None)
        assert done is not None
        assert done["cached"] is False

    # ── 5. add_ai_message raises in finally block ─────────────────────────────

    async def test_redis_ai_message_write_failure_response_still_returned(
        self, client, stream_mocks
    ):
        """
        When add_ai_message raises inside the finally block (after stream
        completes) the exception is caught and logged.  The client must already
        have received a valid done event — the failure is invisible to the caller.
        """
        with patch("main.add_ai_message", side_effect=Exception("Redis write failed")), \
             patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            events = await collect_stream(client, {
                "query": "What is the leave policy?",
                "conversation_id": TEST_CONV_ID,
            })

        done = next((e for e in events if e["type"] == "done"), None)
        assert done is not None
        assert done["cached"] is False
        # Chunks still arrived before the finally block failure
        assert any(e["type"] == "chunk" for e in events)

    # ── 6. set_cached_query raises in finally block ───────────────────────────

    async def test_redis_cache_write_failure_response_still_returned(
        self, client, stream_mocks
    ):
        """
        When set_cached_query raises (Redis write error during cache population)
        the exception is caught silently.  The response the client received is
        unaffected — the done event is already streamed before the cache write.
        """
        with patch("main.set_cached_query", side_effect=Exception("Cache write error")), \
             patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            events = await collect_stream(client, {
                "query": "What is the leave policy?",
                "conversation_id": TEST_CONV_ID,
            })

        assert any(e["type"] == "done" for e in events)
        assert any(e["type"] == "chunk" for e in events)

    # ── 7. Complete Redis outage — all ops fail ────────────────────────────────

    async def test_full_redis_outage_degrades_gracefully(
        self, client, stream_mocks
    ):
        """
        When every Redis operation fails simultaneously (full outage) the system
        must degrade gracefully:
          - add_user_message failure → ignored
          - get_messages failure     → falls back to get_context (DB)
          - get_cached_query failure → treated as cache miss
          - add_ai_message failure   → ignored in finally
          - set_cached_query failure → ignored in finally
          - save_message (DB)        → succeeds (DB is independent of Redis)
          - Client receives          → full valid SSE response
        """
        from types import SimpleNamespace
        db_message = SimpleNamespace(role="user", content="prior question from DB")
        spy_get_context  = MagicMock(return_value=[db_message])
        spy_save_message = MagicMock()
        redis_error      = Exception("Redis: connection refused")

        with patch("main.add_user_message",  side_effect=redis_error), \
             patch("main.get_messages",       side_effect=redis_error), \
             patch("main.get_context",        spy_get_context), \
             patch("main.get_cached_query",   side_effect=redis_error), \
             patch("main.add_ai_message",     side_effect=redis_error), \
             patch("main.set_cached_query",   side_effect=redis_error), \
             patch("main.save_message",       spy_save_message), \
             patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            events = await collect_stream(client, {
                "query": "What is the leave policy?",
                "conversation_id": TEST_CONV_ID,
            })

        # DB context fallback used
        spy_get_context.assert_called_once()
        # DB save succeeded independently of Redis
        spy_save_message.assert_called_once()
        # Full LLM response delivered to client
        done = next((e for e in events if e["type"] == "done"), None)
        assert done is not None
        assert done["cached"] is False
        chunk_text = "".join(e["content"] for e in events if e["type"] == "chunk")
        assert "Annual leave" in chunk_text

    # ── 8. DB save is not skipped when Redis fails ────────────────────────────

    async def test_redis_failure_never_skips_db_save(
        self, client, stream_mocks
    ):
        """
        Even when Redis fails for both the AI message write (add_ai_message)
        and the query cache (set_cached_query), the PostgreSQL save_message call
        must still execute — DB persistence is the source of truth and must not
        depend on Redis availability.
        """
        spy_save = MagicMock()
        redis_error = Exception("Redis down")

        with patch("main.add_ai_message",  side_effect=redis_error), \
             patch("main.set_cached_query", side_effect=redis_error), \
             patch("main.save_message",     spy_save), \
             patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            await collect_stream(client, {
                "query": "What is the leave policy?",
                "conversation_id": TEST_CONV_ID,
            })

        # DB save must be called exactly once — Redis failures must not skip it
        spy_save.assert_called_once()


# ═════════════════════════════════════════════════════════════════════════════
# GET /conversations
# ═════════════════════════════════════════════════════════════════════════════

class TestListConversations:

    # ── Happy path ────────────────────────────────────────────────────────────

    async def test_list_returns_conversations_for_company(self, client):
        """
        GET /conversations returns a list scoped to the JWT company_id.
        Verifies the response shape: success, count, data array.
        """
        with patch("main.get_conversations", return_value=[FAKE_CONVERSATION]):
            response = await client.get("/conversations")

        assert response.status_code == 200
        body = response.json()
        assert body["success"] is True
        assert body["count"] == 1
        assert len(body["data"]) == 1
        assert body["data"][0]["id"] == TEST_CONV_ID
        assert body["data"][0]["company_id"] == TEST_COMPANY_ID

    # ── Empty list ────────────────────────────────────────────────────────────

    async def test_list_returns_empty_when_no_conversations(self, client):
        """When no conversations exist the response has count=0 and data=[]."""
        with patch("main.get_conversations", return_value=[]):
            response = await client.get("/conversations")

        assert response.status_code == 200
        body = response.json()
        assert body["success"] is True
        assert body["count"] == 0
        assert body["data"] == []

    # ── Company scoping ───────────────────────────────────────────────────────

    async def test_list_passes_company_id_from_jwt(self, client):
        """
        get_conversations must be called with the company_id extracted from
        the JWT payload — not any hardcoded or client-supplied value.
        """
        spy = MagicMock(return_value=[])
        with patch("main.get_conversations", spy):
            await client.get("/conversations")

        # Second positional arg is company_id (first is the db session)
        called_company_id = spy.call_args[0][1]
        assert called_company_id == TEST_COMPANY_ID

    # ── No auth ───────────────────────────────────────────────────────────────

    async def test_list_no_auth_returns_401_or_422(self, unauth_client):
        """Unauthenticated request must be rejected."""
        response = await unauth_client.get("/conversations")
        assert response.status_code in (401, 422)

    # ── Invalid token ─────────────────────────────────────────────────────────

    async def test_list_invalid_jwt_returns_401(self, unauth_client):
        """Malformed JWT must return 401."""
        response = await unauth_client.get(
            "/conversations",
            headers={"Authorization": "Bearer bad.token.here"},
        )
        assert response.status_code == 401


# ═════════════════════════════════════════════════════════════════════════════
# GET /conversations/{conversation_id}
# ═════════════════════════════════════════════════════════════════════════════

class TestGetConversation:

    # ── Happy path ────────────────────────────────────────────────────────────

    async def test_get_conversation_returns_history(self, client):
        """GET /conversations/{id} returns the full message history."""
        with patch("main.get_full_history", return_value=[{"role": "user", "content": "hi"}]):
            response = await client.get(f"/conversations/{TEST_CONV_ID}")

        assert response.status_code == 200
        body = response.json()
        assert body["success"] is True
        assert body["conversation_id"] == TEST_CONV_ID

    # ── Not found (nonexistent OR belongs to another company — same 404) ──────

    async def test_get_conversation_not_found_returns_404(self, client):
        """
        get_full_history returning [] must yield 404 — this covers BOTH a
        genuinely nonexistent conversation_id AND one that exists but belongs
        to another company (get_full_history is company_id-scoped, so the two
        cases are indistinguishable to the caller by design — no existence
        leak across companies).
        """
        with patch("main.get_full_history", return_value=[]):
            response = await client.get(f"/conversations/{TEST_CONV_ID}")

        assert response.status_code == 404

    # ── Company scoping (IDOR regression) ──────────────────────────────────────

    async def test_get_conversation_passes_company_id_from_jwt(self, client):
        """
        get_full_history must be called with the company_id extracted from the
        JWT payload, not just the raw conversation_id — otherwise any
        authenticated user could read another company's conversation by id.
        """
        spy = MagicMock(return_value=[{"role": "user", "content": "hi"}])
        with patch("main.get_full_history", spy):
            await client.get(f"/conversations/{TEST_CONV_ID}")

        # get_full_history(db, conversation_id, company_id, limit)
        called_conversation_id = spy.call_args[0][1]
        called_company_id = spy.call_args[0][2]
        assert called_conversation_id == TEST_CONV_ID
        assert called_company_id == TEST_COMPANY_ID

    # ── No auth ───────────────────────────────────────────────────────────────

    async def test_get_conversation_no_auth_returns_401_or_422(self, unauth_client):
        """Unauthenticated request must be rejected."""
        response = await unauth_client.get(f"/conversations/{TEST_CONV_ID}")
        assert response.status_code in (401, 422)


# ═════════════════════════════════════════════════════════════════════════════
# DELETE /conversations/{conversation_id}
# ═════════════════════════════════════════════════════════════════════════════

class TestDeleteConversation:

    # ── Happy path ────────────────────────────────────────────────────────────

    async def test_delete_existing_conversation_returns_success(self, client):
        """
        DELETE /conversations/{id} soft-deletes the record and returns
        {"success": true, "message": "Conversation <id> deleted"}.
        """
        with patch("main.delete_conversation_from_db", return_value=True):
            response = await client.delete(f"/conversations/{TEST_CONV_ID}")

        assert response.status_code == 200
        body = response.json()
        assert body["success"] is True
        assert TEST_CONV_ID in body["message"]

    # ── Not found ─────────────────────────────────────────────────────────────

    async def test_delete_nonexistent_conversation_returns_404(self, client):
        """
        When delete_conversation_from_db returns False (record not found or
        already deleted) the endpoint must respond with HTTP 404.
        """
        with patch("main.delete_conversation_from_db", return_value=False):
            response = await client.delete("/conversations/does-not-exist")

        assert response.status_code == 404

    # ── Correct conversation_id forwarded ─────────────────────────────────────

    async def test_delete_passes_correct_conversation_id(self, client):
        """The conversation_id from the URL path must reach the DB service."""
        target_id = "specific-conv-id-xyz"
        spy = MagicMock(return_value=True)
        with patch("main.delete_conversation_from_db", spy):
            await client.delete(f"/conversations/{target_id}")

        # Second positional arg is conversation_id (first is db session)
        assert spy.call_args[0][1] == target_id

    # ── Company scoping (IDOR regression) ──────────────────────────────────────

    async def test_delete_passes_company_id_from_jwt(self, client):
        """
        delete_conversation_from_db must be called with the company_id
        extracted from the JWT payload — otherwise any authenticated user
        could soft-delete another company's conversation by id.
        """
        spy = MagicMock(return_value=True)
        with patch("main.delete_conversation_from_db", spy):
            await client.delete(f"/conversations/{TEST_CONV_ID}")

        # delete_conversation_from_db(db, conversation_id, company_id)
        called_company_id = spy.call_args[0][2]
        assert called_company_id == TEST_COMPANY_ID

    # ── Soft delete, not hard delete ─────────────────────────────────────────

    async def test_delete_delegates_to_soft_delete_service(self, client):
        """
        The endpoint must call delete_conversation_from_db exactly once.
        That function sets is_deleted=1 — the row is never physically removed.
        """
        spy = MagicMock(return_value=True)
        with patch("main.delete_conversation_from_db", spy):
            response = await client.delete(f"/conversations/{TEST_CONV_ID}")

        assert response.status_code == 200
        spy.assert_called_once()

    # ── No auth ───────────────────────────────────────────────────────────────

    async def test_delete_no_auth_returns_401_or_422(self, unauth_client):
        """Unauthenticated delete request must be rejected."""
        response = await unauth_client.delete(f"/conversations/{TEST_CONV_ID}")
        assert response.status_code in (401, 422)

    # ── Invalid token ─────────────────────────────────────────────────────────

    async def test_delete_invalid_jwt_returns_401(self, unauth_client):
        """Malformed JWT on delete must return 401."""
        response = await unauth_client.delete(
            f"/conversations/{TEST_CONV_ID}",
            headers={"Authorization": "Bearer not.a.real.token"},
        )
        assert response.status_code == 401


# ═════════════════════════════════════════════════════════════════════════════
# Token quota enforcement
# ═════════════════════════════════════════════════════════════════════════════

class TestQuotaEnforcement:

    async def test_quota_exceeded_blocks_before_llm_call(self, client, stream_mocks):
        """A breached quota must return 429 without ever invoking the LangGraph
        pipeline (i.e. zero additional token spend on a blocked request).

        enforce_token_quota raises HTTPException itself when blocked (the route
        never inspects the returned dict to decide), so the override must raise
        too, exactly like the real dependency does."""
        from fastapi import HTTPException

        def _raise_quota_exceeded():
            raise HTTPException(status_code=429, detail={
                "error": "quota_exceeded",
                "message": "Token quota exceeded.",
                "breaches": [{"period": "daily", "limit": 1000, "used": 1000,
                              "reset_at": "2026-06-19T00:00:00+00:00"}],
            })

        app.dependency_overrides[enforce_token_quota] = _raise_quota_exceeded

        astream_spy = MagicMock(side_effect=_hr_astream)
        with patch.object(main.hr_graph, "astream", astream_spy):
            response = await client.post("/hr-assist-stream", json={"query": "What is the leave policy?"})

        assert response.status_code == 429
        body = response.json()
        assert body["detail"]["error"] == "quota_exceeded"
        assert body["detail"]["breaches"][0]["period"] == "daily"
        astream_spy.assert_not_called()

    async def test_quota_allowed_with_warning_surfaces_quota_status_event(self, client, stream_mocks):
        """When under the limit but past the 80% warning threshold, the
        warning must be surfaced as the first SSE event, and the request
        proceeds normally."""
        warned_check = {
            "allowed": True,
            "breaches": [],
            "warnings": [{"period": "daily", "limit": 1000, "used": 850,
                          "percent_used": 0.85, "reset_at": "2026-06-19T00:00:00+00:00"}],
            "policy_source": "user",
        }
        app.dependency_overrides[enforce_token_quota] = lambda: warned_check

        with patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            events = await collect_stream(client, {"query": "What is the leave policy?"})

        quota_event = next(e for e in events if e["type"] == "quota_status")
        assert quota_event["warnings"][0]["period"] == "daily"
        assert any(e["type"] == "done" for e in events)
