"""Smoke tests for create_adapter_app() factory."""

import pytest
from fastapi import FastAPI

from entr_adapter_core.app import create_adapter_app

from tests.mock_handler import MockProcessHandler


class TestAppFactory:

    def test_create_adapter_app_returns_fastapi_app(self, mock_handlers):
        app = create_adapter_app(handlers=mock_handlers)
        assert isinstance(app, FastAPI)

    def test_app_has_process_endpoint(self, mock_handlers):
        app = create_adapter_app(handlers=mock_handlers)
        routes = [r.path for r in app.routes]
        assert "/process" in routes

    def test_app_has_health_endpoint(self, mock_handlers):
        app = create_adapter_app(handlers=mock_handlers)
        routes = [r.path for r in app.routes]
        assert "/health" in routes

    def test_app_has_list_documents_endpoint(self, mock_handlers):
        app = create_adapter_app(handlers=mock_handlers)
        routes = [r.path for r in app.routes]
        assert "/list_documents" in routes

    def test_app_has_download_document_endpoint(self, mock_handlers):
        app = create_adapter_app(handlers=mock_handlers)
        routes = [r.path for r in app.routes]
        assert "/download_document" in routes

    def test_app_with_no_handlers_raises(self):
        with pytest.raises(ValueError, match="At least one handler"):
            create_adapter_app(handlers={})

    @pytest.mark.asyncio
    async def test_app_with_startup_callback(self):
        started = []

        async def on_start():
            started.append(True)

        app = create_adapter_app(
            handlers={"mock": MockProcessHandler()},
            on_startup=[on_start],
        )

        # Trigger lifespan directly (httpx doesn't trigger ASGI lifespan)
        async with app.router.lifespan_context(app):
            assert started == [True]

    @pytest.mark.asyncio
    async def test_app_with_shutdown_callback(self):
        stopped = []

        async def on_stop():
            stopped.append(True)

        app = create_adapter_app(
            handlers={"mock": MockProcessHandler()},
            on_shutdown=[on_stop],
        )

        async with app.router.lifespan_context(app):
            assert stopped == []  # Not yet

        assert stopped == [True]  # After shutdown

    @pytest.mark.asyncio
    async def test_app_startup_failure_is_fatal(self):
        async def failing_start():
            raise RuntimeError("Startup failed!")

        app = create_adapter_app(
            handlers={"mock": MockProcessHandler()},
            on_startup=[failing_start],
        )

        with pytest.raises(RuntimeError, match="Startup failed!"):
            async with app.router.lifespan_context(app):
                pass
