"""
URL configuration for flower project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from rest_framework.response import Response
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView
from sse.views import create_sse_event, push_test_event, get_sse_status, shutdown_sse
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    # TokenRefreshView,
)

# 自定义后台站点标题（simpleui 也会读取）
admin.site.site_header = "宇问科技"
admin.site.site_title = "宇问科技"
admin.site.index_title = "管理后台"

class CustomTokenObtainPairView(TokenObtainPairView):
    """自定义登录视图"""

    def post(self, request, *args, **kwargs):
        try:
            resp = super().post(request, *args, **kwargs)
            if resp.status_code == 200:
                srz = self.get_serializer(data=request.data)
                srz.is_valid()
                user = srz.user

                if not hasattr(user, 'employee'):
                    # 非员工用户，直接返回登录失败
                    return Response({'detail': '无绑定的员工身份'}, status=401)

            return resp
        except Exception as e:
            return Response({'detail': '无法登录'}, status=400)


urlpatterns = [
    # JWT 登录
    path('api/auth/login/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'),
    # path('api/auth/refresh/', TokenRefreshView.as_view(), name='token_refresh'),

    # API 文档
    path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
    path('api/docs/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),

    path('admin/', admin.site.urls),
    path('api/v1/', include('api_v1.urls')),
    path('api/v2/', include('api_v2.urls')),
    path('api/backend/', include('api_man.urls')),

    # sse 相关端点
    path('sse/', create_sse_event, name='sse_event'),
    path('sse/push/', push_test_event, name='push_sse_event'),
    path('sse/status/', get_sse_status, name='sse_status'),
    path('sse/shutdown/', shutdown_sse, name='shutdown_sse'),
]
