from django.http import HttpResponse
from django.test import RequestFactory, SimpleTestCase
from django.utils import timezone

from core.middleware import TimezoneMiddleware


class TimezoneMiddlewareTest(SimpleTestCase):

    def setUp(self):
        self.factory = RequestFactory()
        self.middleware = TimezoneMiddleware(lambda r: HttpResponse())

    def test_activates_valid_timezone_from_cookie(self):
        captured = {}

        def get_response(request):
            captured["tz"] = str(timezone.get_current_timezone())
            return HttpResponse()

        middleware = TimezoneMiddleware(get_response)
        request = self.factory.get("/")
        request.COOKIES["user_tz"] = "America/New_York"
        middleware(request)
        self.assertEqual(captured["tz"], "America/New_York")

    def test_deactivates_after_response(self):
        # Timezone activation must not leak into subsequent requests
        request = self.factory.get("/")
        request.COOKIES["user_tz"] = "America/New_York"
        self.middleware(request)
        self.assertEqual(str(timezone.get_current_timezone()), "UTC")

    def test_invalid_timezone_cookie_does_not_raise(self):
        request = self.factory.get("/")
        request.COOKIES["user_tz"] = "Not/ATimezone"
        self.middleware(request)  # must not raise

    def test_missing_cookie_does_not_raise(self):
        request = self.factory.get("/")
        self.middleware(request)  # must not raise
