"""
Public API v1 URL Configuration

All endpoints are prefixed with /api/v1/

API Documentation:
- Schema: /api/v1/schema/
- Interactive docs: /api/v1/docs/
"""

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from drf_spectacular.views import (
    SpectacularAPIView,
    SpectacularSwaggerView,
    SpectacularRedocView,
)
from rest_framework.permissions import AllowAny

from .views import (
    APITokenViewSet,
    PublicBusinessView,
    PublicServiceViewSet,
    PublicResourceViewSet,
    AvailabilityView,
    PublicAppointmentViewSet,
    PublicCustomerViewSet,
    WebhookViewSet,
)

app_name = 'public_api'

# Router for viewsets
router = DefaultRouter()
router.register(r'tokens', APITokenViewSet, basename='api-tokens')
router.register(r'services', PublicServiceViewSet, basename='services')
router.register(r'resources', PublicResourceViewSet, basename='resources')
router.register(r'appointments', PublicAppointmentViewSet, basename='appointments')
router.register(r'customers', PublicCustomerViewSet, basename='customers')
router.register(r'webhooks', WebhookViewSet, basename='webhooks')

class PublicSchemaView(SpectacularAPIView):
    """Public API schema with no authentication required."""
    permission_classes = [AllowAny]
    authentication_classes = []


class PublicSwaggerView(SpectacularSwaggerView):
    """Public Swagger UI with no authentication required."""
    permission_classes = [AllowAny]
    authentication_classes = []


class PublicRedocView(SpectacularRedocView):
    """Public ReDoc with no authentication required."""
    permission_classes = [AllowAny]
    authentication_classes = []


urlpatterns = [
    # OpenAPI Schema & Documentation (public, no auth required)
    path('schema/', PublicSchemaView.as_view(
        urlconf='smoothschedule.platform.api.urls',
        custom_settings={
            'TITLE': 'SmoothSchedule Public API',
            'DESCRIPTION': '''
# SmoothSchedule Public API v1

This API allows third-party integrations to access business data and manage appointments.

## Authentication

All requests must include an API token in the Authorization header:

```
Authorization: Bearer ss_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

API tokens can be created in the business settings. Each token has specific scopes
that determine what operations it can perform.

## Rate Limiting

- **Global limit:** 1000 requests per hour
- **Burst limit:** 100 requests per minute

Rate limit headers are included in every response:
- `X-RateLimit-Limit`: Total requests allowed per hour
- `X-RateLimit-Remaining`: Requests remaining
- `X-RateLimit-Reset`: Unix timestamp when the limit resets

## Webhooks

Subscribe to real-time event notifications by creating webhook subscriptions.
All webhooks include an HMAC-SHA256 signature in the `X-Webhook-Signature` header
for verification.

## Error Responses

All errors follow this format:

```json
{
  "error": "error_code",
  "message": "Human-readable message",
  "details": { "field": ["error"] }
}
```

## Scopes

| Scope | Description |
|-------|-------------|
| `services:read` | View services and pricing |
| `resources:read` | View resources and staff |
| `availability:read` | Check time slot availability |
| `bookings:read` | View appointments |
| `bookings:write` | Create, update, cancel appointments |
| `customers:read` | View customer information |
| `customers:write` | Create and update customers |
| `business:read` | View business information |
| `webhooks:manage` | Manage webhook subscriptions |
''',
            'VERSION': '1.0.0',
            'CONTACT': {
                'name': 'API Support',
                'email': 'api-support@smoothschedule.com',
            },
            'TAGS': [
                {'name': 'Business', 'description': 'Business information'},
                {'name': 'Services', 'description': 'Service management'},
                {'name': 'Resources', 'description': 'Resource/staff management'},
                {'name': 'Availability', 'description': 'Availability checking'},
                {'name': 'Appointments', 'description': 'Appointment/booking management'},
                {'name': 'Customers', 'description': 'Customer management'},
                {'name': 'Webhooks', 'description': 'Webhook subscriptions'},
                {'name': 'Tokens', 'description': 'API token management'},
            ],
        }
    ), name='schema'),
    path('docs/', PublicSwaggerView.as_view(url_name='public_api:schema'), name='swagger-ui'),
    path('redoc/', PublicRedocView.as_view(url_name='public_api:schema'), name='redoc'),

    # API Endpoints
    path('business/', PublicBusinessView.as_view(), name='business'),
    path('availability/', AvailabilityView.as_view(), name='availability'),

    # ViewSet routes
    path('', include(router.urls)),
]
