"""Auth resource for the MLD API client."""

from __future__ import annotations

from typing import Any

from mld_sdk.client._config import remove_token, store_token
from mld_sdk.client._http import HTTPClient


class AuthAPI:
    """Authentication operations against the MLD platform."""

    def __init__(self, http: HTTPClient) -> None:
        self._http = http

    def login(self, username: str, password: str) -> dict[str, Any]:
        """Authenticate with username/password.

        Stores the returned JWT token in ~/.config/mld/credentials.json
        and configures the HTTP client for subsequent requests.

        Returns the full login response (access_token, expires_in, user).
        """
        data = self._http.post(
            "/auth/login",
            json={
                "username": username,
                "password": password,
            },
        )
        token = data["access_token"]
        expires_in = data.get("expires_in")

        self._http.set_token(token)

        # Compute approximate expiry for storage
        expires_at = None
        if expires_in:
            from datetime import datetime, timedelta, timezone

            expires_at = (datetime.now(timezone.utc) + timedelta(seconds=expires_in)).isoformat()

        store_token(self._http.base_url, token, username, expires_at)
        return data

    def logout(self) -> None:
        """Clear stored credentials for the current host."""
        try:
            self._http.post("/auth/logout")
        except Exception:
            pass  # Best-effort server-side logout
        remove_token(self._http.base_url)
        self._http.set_token(None)

    def verify(self) -> dict[str, Any]:
        """Verify the current token. Returns token info with user details."""
        return self._http.get("/auth/verify")

    def refresh(self) -> dict[str, Any]:
        """Refresh the current token. Returns new token info."""
        data = self._http.post("/auth/refresh")
        new_token = data.get("access_token")
        if new_token:
            self._http.set_token(new_token)
        return data

    def whoami(self) -> dict[str, Any]:
        """Return the current user info. Alias for verify()."""
        return self.verify()

    def config(self) -> dict[str, Any]:
        """Get public auth configuration (no auth required)."""
        return self._http.get("/auth/config")
