from __future__ import annotations

import unittest
from pathlib import Path
from types import SimpleNamespace

from fastapi import FastAPI
from fastapi.templating import Jinja2Templates
from httpx import ASGITransport, AsyncClient

from app.auth import get_current_user
from app.routes import pages


class RipsOperationalPageTest(unittest.IsolatedAsyncioTestCase):
    async def asyncSetUp(self) -> None:
        self.app = FastAPI()
        self.app.include_router(pages.router)

        async def override_current_user():
            return SimpleNamespace(username="auditor", role="auditor")

        self.app.dependency_overrides[get_current_user] = override_current_user
        self.app.state.services = SimpleNamespace(
            templates=Jinja2Templates(directory=str(Path(__file__).resolve().parents[1] / "web"))
        )
        self.transport = ASGITransport(app=self.app)

    async def asyncTearDown(self) -> None:
        self.app.dependency_overrides.clear()

    async def test_rips_operativo_page_renders_with_bootstrap(self) -> None:
        async with AsyncClient(transport=self.transport, base_url="http://testserver") as client:
            response = await client.get("/rips/operativo?case_key=CASE-123")

        self.assertEqual(response.status_code, 200)
        self.assertIn("Consola RIPS", response.text)
        self.assertIn("CASE-123", response.text)
        self.assertIn("Guardar plantilla", response.text)
        self.assertIn('/static/js/user-menu.js', response.text)
        self.assertNotIn('data-app-shell-sidebar', response.text)
        self.assertNotIn('/static/js/app-shell.js', response.text)
        self.assertNotIn('class="ui-header__leading"', response.text)
        self.assertIn("Volver a casos", response.text)
        self.assertIn('data-user-menu-root', response.text)

    async def test_consulta_page_redirects_to_dashboard(self) -> None:
        async with AsyncClient(transport=self.transport, base_url="http://testserver") as client:
            response = await client.get("/consulta", follow_redirects=False)

        self.assertEqual(response.status_code, 307)
        self.assertEqual(response.headers.get("location"), "/dashboard")
