"""Authentication tools: tms_login, tms_whoami."""

import json

from api_client import ApiError, client


def register(mcp):
    @mcp.tool()
    async def tms_login(email: str, password: str) -> str:
        """Authenticate with the TMS backend using email and password.
        Caches the JWT token in-memory for subsequent tool calls this session.
        Must be called before using any other TMS tool."""
        try:
            data = await client.post("/auth/login", {"email": email, "password": password})
            client.set_token(data["access_token"])
            user = data["user"]
            return (
                f"Logged in as {user['display_name']} ({user['email']}). "
                f"Token cached for this session."
            )
        except ApiError as e:
            return str(e)

    @mcp.tool()
    async def tms_whoami() -> str:
        """Get info about the currently authenticated user.
        Returns user id, email, display name, and account creation date."""
        try:
            data = await client.get("/auth/me")
            return json.dumps(data, indent=2, default=str)
        except ApiError as e:
            return str(e)
