from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import (
    TicketViewSet, TicketCommentViewSet,
    TicketTemplateViewSet, CannedResponseViewSet,
    IncomingTicketEmailViewSet, EmailProviderDetectView,
    TicketEmailAddressViewSet, RefreshTicketEmailsView
)

app_name = 'tickets'

router = DefaultRouter()
# Main tickets endpoint - will be at /api/tickets/
router.register(r'', TicketViewSet, basename='ticket')

# Nested comments route - will be at /api/tickets/{ticket_pk}/comments/
router.register(
    r'(?P<ticket_pk>[^/.]+)/comments',
    TicketCommentViewSet,
    basename='ticket-comment'
)

# Separate router for templates and canned responses
templates_router = DefaultRouter()
templates_router.register(r'', TicketTemplateViewSet, basename='ticket-template')

canned_router = DefaultRouter()
canned_router.register(r'', CannedResponseViewSet, basename='canned-response')

# Router for incoming emails (audit log)
incoming_emails_router = DefaultRouter()
incoming_emails_router.register(r'', IncomingTicketEmailViewSet, basename='incoming-email')

# Router for email addresses
email_addresses_router = DefaultRouter()
email_addresses_router.register(r'', TicketEmailAddressViewSet, basename='email-address')

urlpatterns = [
    # Incoming emails audit log - must be BEFORE router.urls
    path('incoming-emails/', include(incoming_emails_router.urls)),

    # Email addresses (per-business and platform email configuration)
    path('email-addresses/', include(email_addresses_router.urls)),

    # Manual email refresh endpoint
    path('refresh-emails/', RefreshTicketEmailsView.as_view(), name='refresh-emails'),

    # Other static paths
    path('templates/', include(templates_router.urls)),
    path('canned-responses/', include(canned_router.urls)),

    # Main tickets router (includes catch-all pattern) - must be LAST
    path('', include(router.urls)),
]