"""Apple OAuth provider — delegates to waft centralized auth service."""

from __future__ import annotations

from urllib.parse import urlencode

from waft_client.config import AuthConfig
from waft_client.models import ProviderInfo
from waft_client.store import AuthStore

INFO = ProviderInfo(id="apple", name="Apple", provider_type="oauth")


def handle_route(
    path: str,
    method: str,
    event: dict,
    store: AuthStore,
    config: AuthConfig,
) -> dict | None:
    """Handle /auth/apple route — redirect to waft auth service."""
    if path == "/auth/apple" and method == "GET":
        return _initiate(event, config)
    return None


def _get_host(event: dict) -> str:
    headers = event.get("headers", {})
    return headers.get("x-forwarded-host") or headers.get("host", "localhost")


def _initiate(event: dict, config: AuthConfig) -> dict:
    """Redirect to the waft auth service to start Apple OAuth."""
    if not config.auth_service_url:
        return {
            "statusCode": 200,
            "headers": {"content-type": "text/html"},
            "body": "<h1>Apple OAuth not configured</h1><p>Set WAFT_AUTH_SERVICE_URL to enable OAuth.</p>",
        }

    host = _get_host(event)
    scheme = "https" if config.cookie_secure else "http"
    redirect_uri = f"{scheme}://{host}{config.callback_path}"

    params = urlencode({
        "app_id": config.app_id,
        "redirect_uri": redirect_uri,
        "provider": "apple",
    })
    url = f"{config.auth_service_url}/auth-service/oauth/apple?{params}"

    return {
        "statusCode": 302,
        "headers": {"location": url},
        "body": "",
    }
