# tests/integration/middleware/test_context_detection_flow.py
"""
Integration tests for request context detection end-to-end flow.

These tests verify that context type (API, ADMIN, VENDOR_DASHBOARD, SHOP, FALLBACK)
is correctly detected through real HTTP requests.

Note: These tests use pre-registered routes in middleware_test_routes.py.
The conftest patches get_db and settings.platform_domain for proper testing.
"""

import pytest

from middleware.context import RequestContext


@pytest.mark.integration
@pytest.mark.middleware
@pytest.mark.context
class TestContextDetectionFlow:
    """Test context type detection through real HTTP requests."""

    # ========================================================================
    # API Context Detection Tests
    # ========================================================================

    def test_api_path_detected_as_api_context(self, client):
        """Test that /api/* paths are detected as API context."""
        response = client.get("/api/middleware-test/context")

        assert response.status_code == 200
        data = response.json()
        assert data["context_type"] == "api"
        assert data["context_enum"] == "API"

    def test_nested_api_path_detected_as_api_context(self, client):
        """Test that nested /api/ paths are detected as API context."""
        response = client.get("/api/middleware-test/nested-context")

        assert response.status_code == 200
        data = response.json()
        assert data["context_type"] == "api"

    # ========================================================================
    # Admin Context Detection Tests
    # ========================================================================

    def test_admin_path_detected_as_admin_context(self, client):
        """Test that /admin/* paths are detected as ADMIN context."""
        response = client.get("/admin/middleware-test/context")

        assert response.status_code == 200
        data = response.json()
        assert data["context_type"] == "admin"
        assert data["context_enum"] == "ADMIN"

    def test_admin_subdomain_detected_as_admin_context(self, client):
        """Test that admin.* subdomain is detected as ADMIN context."""
        response = client.get(
            "/api/middleware-test/admin-subdomain-context",
            headers={"host": "admin.platform.com"},
        )

        assert response.status_code == 200
        data = response.json()
        # Note: API path overrides subdomain, so still API context
        assert data["context_type"] == "api"

    def test_nested_admin_path_detected_as_admin_context(self, client):
        """Test that nested /admin/ paths are detected as ADMIN context."""
        response = client.get("/admin/middleware-test/nested-context")

        assert response.status_code == 200
        data = response.json()
        assert data["context_type"] == "admin"

    # ========================================================================
    # Shop Context Detection Tests
    # ========================================================================
    # Note: Vendor dashboard context detection is tested via unit tests in
    # tests/unit/middleware/test_context.py since /vendor/* integration test
    # routes are shadowed by the catch-all /vendor/{vendor_code}/{slug} route.

    def test_shop_path_with_vendor_detected_as_shop(
        self, client, vendor_with_subdomain
    ):
        """Test that /shop/* paths with vendor are detected as SHOP context."""
        response = client.get(
            "/shop/middleware-test/context",
            headers={"host": f"{vendor_with_subdomain.subdomain}.platform.com"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["context_type"] == "shop"
        assert data["context_enum"] == "SHOP"
        assert data["has_vendor"] is True

    def test_custom_domain_shop_detected(self, client, vendor_with_custom_domain):
        """Test that custom domain shop is detected as SHOP context."""
        response = client.get(
            "/shop/middleware-test/custom-domain-context",
            headers={"host": "customdomain.com"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["context_type"] == "shop"
        # Custom domain may or may not detect vendor depending on is_verified
        if data["vendor_code"]:
            assert data["vendor_code"] == vendor_with_custom_domain.vendor_code

    # ========================================================================
    # Fallback Context Detection Tests
    # ========================================================================

    def test_unknown_path_without_vendor_fallback_context(self, client):
        """Test that API paths without vendor get API context (fallback via API)."""
        response = client.get(
            "/api/middleware-test/fallback-context", headers={"host": "platform.com"}
        )

        assert response.status_code == 200
        data = response.json()
        # API path triggers API context
        assert data["context_type"] == "api"
        assert data["has_vendor"] is False

    # ========================================================================
    # Context Priority Tests (Path takes precedence)
    # ========================================================================

    def test_api_path_overrides_vendor_context(self, client, vendor_with_subdomain):
        """Test that /api/* path sets API context even with vendor subdomain."""
        response = client.get(
            "/api/middleware-test/vendor-priority",
            headers={"host": f"{vendor_with_subdomain.subdomain}.platform.com"},
        )

        assert response.status_code == 200
        data = response.json()
        # API path should set API context
        assert data["context_type"] == "api"
        # Vendor detection depends on middleware order - may or may not be set for API

    def test_admin_path_overrides_vendor_context(self, client, vendor_with_subdomain):
        """Test that /admin/* path sets ADMIN context even with vendor."""
        response = client.get(
            "/admin/middleware-test/vendor-priority",
            headers={"host": f"{vendor_with_subdomain.subdomain}.platform.com"},
        )

        assert response.status_code == 200
        data = response.json()
        # Admin path should override vendor context
        assert data["context_type"] == "admin"

    # ========================================================================
    # Context Detection with Clean Path Tests
    # ========================================================================
    # Note: Vendor dashboard priority over shop context is tested via unit tests
    # in tests/unit/middleware/test_context.py (test_vendor_dashboard_priority_over_shop)

    def test_context_uses_clean_path_for_detection(self, client, vendor_with_subdomain):
        """Test that context detection uses clean_path, not original path."""
        response = client.get(
            "/api/middleware-test/clean-path-context",
            headers={"host": "localhost:8000"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["context_type"] == "api"

    # ========================================================================
    # Context Enum Value Tests
    # ========================================================================

    def test_context_type_is_enum_instance(self, client):
        """Test that context_type is a RequestContext enum instance."""
        response = client.get("/api/middleware-test/enum")

        assert response.status_code == 200
        data = response.json()
        assert data["is_enum"] is True
        assert data["enum_name"] == "API"
        assert data["enum_value"] == "api"
