"""Authentication helpers for D365 Commerce Scale Unit."""

from __future__ import annotations

import msal


class AzureADAuth:
    """Client-credentials OAuth2 flow via Azure AD (MSAL)."""

    def __init__(
        self,
        tenant_id: str,
        client_id: str,
        client_secret: str,
        resource_id: str,
    ) -> None:
        self.resource_id = resource_id
        self._app = msal.ConfidentialClientApplication(
            client_id,
            authority=f"https://login.microsoftonline.com/{tenant_id}",
            client_credential=client_secret,
        )

    def get_token(self) -> str:
        """Acquire an access token (cached when possible)."""
        result = self._app.acquire_token_for_client(
            scopes=[f"{self.resource_id}/.default"],
        )
        if "access_token" not in result:
            error = result.get("error_description", result.get("error", "unknown"))
            raise RuntimeError(f"Failed to acquire token: {error}")
        return result["access_token"]

    def get_headers(self, oun: str) -> dict[str, str]:
        """Return headers dict with Bearer token and OUN."""
        return {
            "Authorization": f"Bearer {self.get_token()}",
            "OUN": oun,
            "Content-Type": "application/json",
        }


class RetailServerAuth:
    """Simple token-based auth for Retail Server scenarios.

    Use this when you already have a valid token (e.g. from an
    employee/device activation flow).
    """

    def __init__(self, token: str) -> None:
        self._token = token

    def get_token(self) -> str:
        return self._token

    def get_headers(self, oun: str) -> dict[str, str]:
        return {
            "Authorization": f"Bearer {self._token}",
            "OUN": oun,
            "Content-Type": "application/json",
        }
