"""Tests for the notification SSE endpoint."""
from __future__ import annotations

import json
from unittest import mock

import pytest
from django.contrib.auth import get_user_model
from django.test import Client
from django.urls import reverse

User = get_user_model()


@pytest.fixture
def user(db):
    return User.objects.create_user(
        email="sse@example.com",
        password="x",
        first_name="S",
        last_name="E",
    )


def test_stream_requires_authentication(db):
    c = Client()
    resp = c.get(reverse("core:notification_stream"))
    # login_required redirects anonymous users (302).
    assert resp.status_code in (302, 401, 403)


def test_stream_emits_initial_snapshot(user, settings):
    settings.NOTIFICATION_SSE_INTERVAL_SECONDS = 1
    settings.NOTIFICATION_SSE_MAX_SECONDS = 1
    c = Client()
    c.force_login(user)
    resp = c.get(reverse("core:notification_stream"))
    assert resp["content-type"].startswith("text/event-stream")
    # Pull the first event off the streaming generator.
    chunks = []
    for chunk in resp.streaming_content:
        chunks.append(chunk.decode("utf-8"))
        if len(chunks) >= 1:
            break
    body = "".join(chunks)
    assert "event: notification" in body
    assert '"unread"' in body
