"""§8 — Anonymous call-detail recruiting layout.

Verifies the template-flip pattern on ``CallDetailView``: anonymous
visitors land on the recruiting-poster variant; authenticated users keep
the in-app detail page.
"""
from datetime import timedelta

import pytest
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils import timezone

from apps.rims.grants.models import GrantCall

User = get_user_model()


def _make_call(status=GrantCall.Status.PUBLISHED, slug="recruiting"):
    return GrantCall.objects.create(
        title="Recruiting Surface Call",
        slug=slug,
        opens_at=timezone.now() - timedelta(days=1),
        closes_at=timezone.now() + timedelta(days=14),
        status=status,
        description="<p>Why this matters.</p>",
    )


@pytest.fixture
def staff_user(db):
    return User.objects.create_user(
        email="staff@example.com", password="pw", is_staff=True
    )


@pytest.mark.django_db
def test_anonymous_visitor_sees_recruiting_template(client):
    call = _make_call()
    response = client.get(reverse("rims_grants:call_detail", args=[call.slug]))
    assert response.status_code == 200
    # CallDetailView.get_template_names flips to the public variant when
    # the request is unauthenticated.
    template_names = [t.name for t in response.templates]
    assert "grants/call_detail_public.html" in template_names
    assert "grants/call_detail.html" not in template_names


@pytest.mark.django_db
def test_authenticated_visitor_sees_full_call_detail(client, staff_user):
    call = _make_call(slug="auth-view")
    client.force_login(staff_user)
    response = client.get(reverse("rims_grants:call_detail", args=[call.slug]))
    assert response.status_code == 200
    template_names = [t.name for t in response.templates]
    assert "grants/call_detail.html" in template_names
    assert "grants/call_detail_public.html" not in template_names


@pytest.mark.django_db
def test_anonymous_cannot_see_draft_call(client):
    """Public surface is RUFORUM's marketing window — drafts and in-flight
    awarding states stay private."""
    draft = _make_call(status=GrantCall.Status.DRAFT, slug="hidden-draft")
    awarding = _make_call(status=GrantCall.Status.AWARDING, slug="hidden-awarding")
    for call in (draft, awarding):
        response = client.get(reverse("rims_grants:call_detail", args=[call.slug]))
        assert response.status_code == 404


@pytest.mark.django_db
def test_anonymous_sees_closed_call_with_closed_pill(client):
    """Closed calls remain visible — donors and partners often link to them
    in retrospectives — but the recruiting CTA flips to the closed state."""
    call = _make_call(status=GrantCall.Status.CLOSED, slug="closed-but-public")
    response = client.get(reverse("rims_grants:call_detail", args=[call.slug]))
    assert response.status_code == 200
    body = response.content.decode()
    assert "Submissions closed" in body
