"""Generate login url."""

from typing import Annotated

from ab_core.auth_client.oauth2.client import OAuth2Client
from ab_core.auth_client.oauth2.client.pkce import PKCEOAuth2Client
from ab_core.auth_client.oauth2.client.standard import StandardOAuth2Client
from ab_core.auth_client.oauth2.schema.authorize import (
    OAuth2AuthorizeResponse,
    OAuth2BuildAuthorizeRequest,
    PKCEAuthorizeResponse,
    PKCEBuildAuthorizeRequest,
)
from ab_core.cache.caches.base import CacheSession
from ab_core.cache.session_context import cache_session_sync  # your DI dep that yields a session
from ab_core.dependency import Depends
from fastapi import APIRouter
from fastapi import Depends as FDepends

router = APIRouter(prefix="/login", tags=["Auth"])


@router.get(
    "",
    response_model=OAuth2AuthorizeResponse | PKCEAuthorizeResponse,
)
async def get_login_url(
    auth_client: Annotated[OAuth2Client, Depends(OAuth2Client, persist=True)],
    cache_session: Annotated[CacheSession, FDepends(cache_session_sync)],
    # optional knobs (you can also load these from env/settings if you prefer)
    scope: str = "openid email profile",
    response_type: str = "code",
    identity_provider: str | None = "Google",
):
    """Build an OIDC authorize URL (Standard or PKCE) using the shared auth client.

    If PKCE, a fresh verifier/challenge is generated and (optionally) persisted to cache keyed by `state`.
    """
    extra = {"identity_provider": identity_provider} if identity_provider else None

    if isinstance(auth_client, PKCEOAuth2Client):
        req = PKCEBuildAuthorizeRequest(
            scope=scope,
            response_type=response_type,
            extra_params=extra,
            pkce=None,  # per-request PKCE generated by the client
        )
        return auth_client.build_authorize_request(req, cache_session=cache_session)

    elif isinstance(auth_client, StandardOAuth2Client):
        req = OAuth2BuildAuthorizeRequest(
            scope=scope,
            response_type=response_type,
            extra_params=extra,
        )
        return auth_client.build_authorize_request(req, cache_session=cache_session)

    # If you later add more client types, handle them here
    raise TypeError(f"Unsupported OAuth2 client type: {type(auth_client).__name__}")
