from __future__ import annotations

import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch

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

from app.routes import users


class LoginPageTest(unittest.IsolatedAsyncioTestCase):
    async def asyncSetUp(self) -> None:
        self.app = FastAPI()
        self.app.include_router(users.router)
        self.app.state.services = SimpleNamespace(
            templates=Jinja2Templates(directory=str(Path(__file__).resolve().parents[1] / "web"))
        )
        self.transport = ASGITransport(app=self.app)

    async def test_login_page_renders_with_design_system_assets(self) -> None:
        async with AsyncClient(transport=self.transport, base_url="http://testserver") as client:
            response = await client.get("/login?next=%2Fconsulta")

        self.assertEqual(response.status_code, 200)
        self.assertIn('/static/css/globals.css', response.text)
        self.assertIn('/static/css/login.css', response.text)
        self.assertIn('/static/js/login.js', response.text)
        self.assertIn('name="next" value="/consulta"', response.text)
        self.assertIn("Iniciar sesión", response.text)

    async def test_login_page_renders_invalid_credentials_error(self) -> None:
        with patch("app.routes.users.authenticate_user", new=AsyncMock(return_value=None)):
            async with AsyncClient(transport=self.transport, base_url="http://testserver") as client:
                response = await client.post(
                    "/login",
                    data={"username": "auditor", "password": "bad-pass", "next": "/dashboard"},
                )

        self.assertEqual(response.status_code, 200)
        self.assertIn("Credenciales inválidas", response.text)
        self.assertIn('role="alert"', response.text)


if __name__ == "__main__":
    unittest.main()
