# Copyright 2025 Softwell S.r.l.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tests for Dispatcher lazy auth — on-demand authentication."""

from unittest.mock import MagicMock

from genro_asgi.server.auth_mixin import BasicAuthMixin
from genro_asgi.server.dispatcher import Dispatcher


class FakeServer(BasicAuthMixin):
    """Minimal server with BasicAuthMixin for lazy auth tests."""

    __slots__ = ("_auth_config", "router", "request_registry")

    def __init__(self, **auth_entries) -> None:
        BasicAuthMixin.__init__(self, **auth_entries)
        self.router = MagicMock()
        self.request_registry = MagicMock()


class TestDispatcherLazyAuth:
    """Tests for Dispatcher._ensure_auth() lazy authentication."""

    def test_lazy_auth_called_when_no_middleware(self) -> None:
        """scope without 'auth' triggers server.authenticate() via _ensure_auth."""
        server = FakeServer(
            bearer={"api_key": {"token": "tk_test", "tags": "read"}},
        )
        dispatcher = Dispatcher(server)
        scope = {
            "type": "http",
            "headers": [(b"authorization", b"Bearer tk_test")],
        }

        dispatcher._ensure_auth(scope)

        assert scope["auth"] is not None
        assert scope["auth"]["identity"] == "api_key"
        assert scope["auth"]["tags"] == ["read"]
        assert scope["auth"]["backend"] == "bearer"
        assert scope["_filters"]["auth_tags"] == ["read"]

    def test_lazy_auth_not_called_when_already_set(self) -> None:
        """scope with 'auth' already set is not re-authenticated."""
        server = FakeServer(
            bearer={"api_key": {"token": "tk_test", "tags": "read"}},
        )
        dispatcher = Dispatcher(server)
        existing_auth = {"identity": "preset", "tags": ["admin"], "backend": "external"}
        scope = {
            "type": "http",
            "headers": [(b"authorization", b"Bearer tk_test")],
            "auth": existing_auth,
        }

        dispatcher._ensure_auth(scope)

        assert scope["auth"] is existing_auth

    def test_lazy_auth_sets_auth_tags_in_scope(self) -> None:
        """_ensure_auth populates scope['_filters']['auth_tags'] with correct tags."""
        server = FakeServer(
            bearer={"admin": {"token": "tk_admin", "tags": "admin,write"}},
        )
        dispatcher = Dispatcher(server)
        scope = {
            "type": "http",
            "headers": [(b"authorization", b"Bearer tk_admin")],
        }

        dispatcher._ensure_auth(scope)

        assert scope["_filters"]["auth_tags"] == ["admin", "write"]
        assert "_headers" in scope
