"""
Views for Orders API.

Authentication is handled by GRAPHENE MIDDLEWARE in settings.py
"""
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from jwt import InvalidTokenError
from graphene_django.views import GraphQLView

from .graphql_middleware import PublicNoAuthMiddleware, TeamJWTMiddleware, UserJWTMiddleware

from .auth import get_bearer_token, scopes_from_payload, validator


@csrf_exempt
def test_jwt_orders(request):
    """Test endpoint for Orders API JWT validation"""

    try:
        token = get_bearer_token(request)
    except InvalidTokenError as exc:
        return JsonResponse({"status": "error", "error": str(exc)}, status=403)

    response = {"token_length": len(token), "token_preview": f"{token[:32]}...{token[-32:]}"}

    try:
        payload = validator.decode(token, audience=getattr(settings, "LOGTO_ORDERS_AUDIENCE", None))
        response.update(
            {
                "status": "ok",
                "payload": payload,
                "user_id": payload.get("sub"),
                "team_uuid": payload.get("team_uuid"),
                "audience": payload.get("aud"),
                "scopes": scopes_from_payload(payload),
            }
        )
        return JsonResponse(response, json_dumps_params={'indent': 2})
    except InvalidTokenError as exc:
        response["status"] = "invalid"
        response["error"] = str(exc)
        return JsonResponse(response, status=403, json_dumps_params={'indent': 2})


class PublicGraphQLView(GraphQLView):
    """Public endpoint - no authentication required."""

    def __init__(self, *args, **kwargs):
        kwargs['middleware'] = [PublicNoAuthMiddleware()]
        super().__init__(*args, **kwargs)


class UserGraphQLView(GraphQLView):
    """User endpoint - requires ID Token."""

    def __init__(self, *args, **kwargs):
        kwargs['middleware'] = [UserJWTMiddleware()]
        super().__init__(*args, **kwargs)


class TeamGraphQLView(GraphQLView):
    """Team endpoint - requires Team Access Token."""

    def __init__(self, *args, **kwargs):
        kwargs['middleware'] = [TeamJWTMiddleware()]
        super().__init__(*args, **kwargs)
