"""AccessLog middleware: still logs tracked paths, write happens off-thread."""

import pytest
from django.contrib.auth import get_user_model
from rest_framework.test import APIClient

from apps.analytics.models import AccessLog

User = get_user_model()


@pytest.mark.django_db
class TestAccessLogMiddleware:
    @pytest.fixture(autouse=True)
    def eager(self, settings):
        settings.BACKGROUND_TASKS_EAGER = True

    def test_tracked_path_logged(self, client):
        client.get("/api/publications/some-id/")
        log = AccessLog.objects.get()
        assert log.resource_type == "publication"
        assert log.resource_id == "some-id"
        assert log.path == "/api/publications/some-id/"
        assert log.method == "GET"

    def test_untracked_path_not_logged(self, client):
        client.get("/api/projects/")
        assert AccessLog.objects.count() == 0

    def test_utm_and_referer_captured(self, client):
        client.get(
            "/api/publications/x/?utm_source=tw&utm_medium=social",
            HTTP_REFERER="https://twitter.com/some/post",
        )
        log = AccessLog.objects.get()
        assert log.utm_source == "tw"
        assert log.utm_medium == "social"
        assert log.referer_host == "twitter.com"
