import json
import jwt
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from jwt import InvalidTokenError

from .auth import get_bearer_token, scopes_from_payload, validator


@csrf_exempt
def test_jwt(request):
    """Тестовый endpoint для проверки JWT токена с подписью."""

    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:
        audience = getattr(settings, "LOGTO_TEAMS_AUDIENCE", None)
        payload = validator.decode(token, audience=audience)
        response.update(
            {
                "status": "ok",
                "header": jwt.get_unverified_header(token),
                "payload": payload,
                "user_id": payload.get("sub"),
                "team_uuid": payload.get("team_uuid"),
                "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})


# GraphQL Views - authentication handled by GRAPHENE MIDDLEWARE

from graphene_django.views import GraphQLView

from .graphql_middleware import (
    M2MNoAuthMiddleware,
    PublicNoAuthMiddleware,
    TeamJWTMiddleware,
    UserJWTMiddleware,
)


def _is_introspection_query(request):
    """Проверяет, является ли запрос introspection (для GraphQL codegen)"""
    if request.method != 'POST':
        return False
    try:
        body = json.loads(request.body.decode('utf-8'))
        query = body.get('query', '')
        return '__schema' in query or '__type' in query
    except Exception:
        return False


class PublicGraphQLView(GraphQLView):
    """GraphQL view for public operations (no authentication)."""

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


class UserGraphQLView(GraphQLView):
    """GraphQL view for user-level operations (ID Token)."""

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


class TeamGraphQLView(GraphQLView):
    """GraphQL view for team-level operations (Access Token)."""

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


class M2MGraphQLView(GraphQLView):
    """GraphQL view for M2M (machine-to-machine) operations.
    No authentication required - used by internal services (Temporal, etc.)
    """

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