"""PRD §4.3.1 — guest preview of published calls.

Regression locks:
- Unauthenticated users can GET `call_detail` / `call_list` for published calls.
- Unauthenticated users cannot POST to `call_apply` (login-required).
- Draft calls remain invisible to anonymous users.
"""
from datetime import timedelta

import pytest
from django.urls import reverse
from django.utils import timezone

from apps.rims.grants.models import GrantCall


@pytest.mark.django_db
def test_anonymous_can_browse_published_call_list(client):
    GrantCall.objects.create(
        title="Preview call",
        slug=f"prev-{int(timezone.now().timestamp())}",
        opens_at=timezone.now() - timedelta(days=1),
        closes_at=timezone.now() + timedelta(days=10),
        status=GrantCall.Status.PUBLISHED,
    )
    resp = client.get(reverse("rims_grants:call_list"))
    assert resp.status_code == 200


@pytest.mark.django_db
def test_anonymous_can_view_published_call_detail(client):
    call = GrantCall.objects.create(
        title="Preview detail",
        slug=f"prev-det-{int(timezone.now().timestamp())}",
        opens_at=timezone.now() - timedelta(days=1),
        closes_at=timezone.now() + timedelta(days=10),
        status=GrantCall.Status.PUBLISHED,
    )
    resp = client.get(reverse("rims_grants:call_detail", kwargs={"slug": call.slug}))
    assert resp.status_code == 200


@pytest.mark.django_db
def test_anonymous_cannot_view_draft_call(client):
    call = GrantCall.objects.create(
        title="Hidden draft",
        slug=f"hid-{int(timezone.now().timestamp())}",
        opens_at=timezone.now() - timedelta(days=1),
        closes_at=timezone.now() + timedelta(days=10),
        status=GrantCall.Status.DRAFT,
    )
    resp = client.get(reverse("rims_grants:call_detail", kwargs={"slug": call.slug}))
    assert resp.status_code == 404


@pytest.mark.django_db
def test_anonymous_apply_post_redirects_to_login(client, institution):
    call = GrantCall.objects.create(
        title="Apply call",
        slug=f"apply-{int(timezone.now().timestamp())}",
        opens_at=timezone.now() - timedelta(days=1),
        closes_at=timezone.now() + timedelta(days=10),
        status=GrantCall.Status.PUBLISHED,
    )
    resp = client.post(
        reverse("rims_grants:call_apply", kwargs={"slug": call.slug}),
        {"institution": institution.pk},
    )
    # LoginRequiredMixin issues a 302 to the login page.
    assert resp.status_code in (302, 301)
    assert "/login" in resp["Location"] or "/accounts/login" in resp["Location"]
