from fastapi import APIRouter, Depends, HTTPException, Query, status, Request from sqlalchemy.orm import Session from typing import List, Optional, Any from app.core.database.db_session import get_db from app.core.permissions.RoleChecker import get_current_user from app.models.UserModel import User from app.services.NotificationGatewayService import NotificationGatewayService from app.schemas.NotificationGateway import ( NotificationDispatchCreate, EntityNotificationDispatchCreate, NotificationResponse, DeadLetterNotificationResponse, WhatsAppSessionStatusResponse, WhatsAppSessionQRResponse ) router = APIRouter(prefix="/api/v1/notifications", tags=["Notification Gateway & OpenWA / ZeptoMail"]) def get_tenant_id(request: Request, current_user: Optional[User] = None) -> str: user_tenant = getattr(current_user, "tenant_id", None) if current_user else None return user_tenant or getattr(request.state, "tenant_id", "tenant_default") @router.post("/dispatch-entity", response_model=List[NotificationResponse], status_code=status.HTTP_201_CREATED) def dispatch_entity_notification( payload: EntityNotificationDispatchCreate, request: Request, db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ) -> Any: """Dispatches a notification for a CRM Quotation, Invoice, or Repair Ticket by resolving entity recipients server-side with idempotency checks.""" tenant_id = get_tenant_id(request, current_user) return NotificationGatewayService.dispatch_entity_notification(db=db, tenant_id=tenant_id, payload=payload) @router.post("/dispatch", response_model=NotificationResponse, status_code=status.HTTP_201_CREATED) def dispatch_notification( payload: NotificationDispatchCreate, request: Request, db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ) -> Any: """Dispatches a raw direct notification via WhatsApp (OpenWA Gateway) or Email (ZeptoMail API).""" tenant_id = get_tenant_id(request, current_user) return NotificationGatewayService.dispatch_notification(db=db, tenant_id=tenant_id, payload=payload) @router.get("/logs", response_model=List[NotificationResponse]) def get_notification_logs( request: Request, skip: int = Query(0, ge=0), limit: int = Query(50, ge=1, le=200), db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ) -> Any: """Retrieves delivery attempt logs and statuses for notifications.""" tenant_id = get_tenant_id(request) return NotificationGatewayService.get_notification_logs(db=db, tenant_id=tenant_id, skip=skip, limit=limit) @router.get("/dlq", response_model=List[DeadLetterNotificationResponse]) def get_dlq_logs( request: Request, skip: int = Query(0, ge=0), limit: int = Query(50, ge=1, le=200), db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ) -> Any: """Retrieves failed notifications stored in Dead Letter Queue (DLQ).""" tenant_id = get_tenant_id(request) return NotificationGatewayService.get_dlq_logs(db=db, tenant_id=tenant_id, skip=skip, limit=limit) @router.post("/dlq/{dlq_id}/resolve", response_model=DeadLetterNotificationResponse) def resolve_dlq_item( dlq_id: str, request: Request, db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ) -> Any: """Marks a Dead Letter Queue item as resolved.""" tenant_id = get_tenant_id(request) return NotificationGatewayService.resolve_dlq(db=db, tenant_id=tenant_id, dlq_id=dlq_id) @router.get("/whatsapp-gateway/status", response_model=WhatsAppSessionStatusResponse) def get_whatsapp_gateway_status( request: Request, session_name: str = Query("default"), db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ) -> Any: """Checks self-hosted OpenWA WhatsApp Web session status and battery level.""" tenant_id = get_tenant_id(request) return NotificationGatewayService.get_whatsapp_status(db=db, tenant_id=tenant_id, session_name=session_name) @router.get("/whatsapp-gateway/qr", response_model=WhatsAppSessionQRResponse) def get_whatsapp_gateway_qr( request: Request, session_name: str = Query("default"), db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ) -> Any: """Retrieves QR code base64 string for linking OpenWA WhatsApp session.""" tenant_id = get_tenant_id(request) return NotificationGatewayService.get_whatsapp_qr(db=db, tenant_id=tenant_id, session_name=session_name) @router.post("/whatsapp-gateway/pairing-code") def get_whatsapp_gateway_pairing_code( request: Request, phone_number: str = Query(..., alias="phoneNumber"), session_name: str = Query("default"), db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ) -> Any: """Generates an authentic WhatsApp 8-character pairing code via OpenWA REST engine.""" tenant_id = get_tenant_id(request) return NotificationGatewayService.get_whatsapp_pairing_code( db=db, tenant_id=tenant_id, phone_number=phone_number, session_name=session_name )