"""
Endpoint: get_app_authorization

Get learning track authorization status for a student.

POST /get-app-authorization

Used by: edupaid/service.py::EdupaidService.get_app_authorization

Reference: edupaid/docs/edupaid/get-app-authorization.yaml
"""

from typing import Any, Dict

from edupaid.http import HttpClient
from edupaid.models.request import EdupaidGetLearningTrackAuthorizationRequest
from edupaid.models.response import EdupaidLearningTrackAuthorizationResponse

from edupaid.logs.logger import configure_logging

log = configure_logging(__name__, log_level="WARNING")


def get_app_authorization(
    http: HttpClient,
    request: EdupaidGetLearningTrackAuthorizationRequest,
) -> EdupaidLearningTrackAuthorizationResponse:
    """
    Get learning track authorization status for a student.

    Verifies the API key, validates input, fetches the learning track and student,
    and returns whether the track is locked, unlocked, scheduled, or defaulted
    along with payment modes and scheduling information.

    Steps:
        1. Serialize the request model to JSON (using camelCase field names)
        2. POST to /get-app-authorization
        3. Parse and return the response as EdupaidLearningTrackAuthorizationResponse

    Args:
        http: HttpClient instance for making API requests.
        request: Request containing studentId and learningTrackId.

    Returns:
        EdupaidLearningTrackAuthorizationResponse with track details and authorization status.
        - track: UnifiedLearningTrack with learningTrackId, learningTrackName, appId, isLocked,
                 and optional paymentModes, scheduledChargeDate, frequency
        - defaulted: Whether the authorization has defaulted
        - status: Authorization status (unlocked, locked, scheduled, defaulted)

    Raises:
        ValidationError: If request body is invalid (400).
        AuthError: If API key is invalid or missing (401).
        NotFoundError: If learning track not found (404).
        ServerError: If server error occurs (5xx).
    """
    log.debug(f"get_app_authorization request: {request}")
    # Serialize request to dict - model fields already use camelCase
    body: Dict[str, Any] = request.model_dump(exclude_none=True)

    # Make POST request to the endpoint
    data: Dict[str, Any] = http.post("/get-app-authorization", json=body)

    log.debug(f"get_app_authorization response: {data}")

    # Parse and return typed response
    return EdupaidLearningTrackAuthorizationResponse.model_validate(data)
