from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from config.database import get_db
from config.settings import settings
from models.notification import PushSubscription
from models.user import User
from schemas.notification import PushSubscriptionCreate, VapidPublicKeyResponse
from utils.security import get_current_active_user

router = APIRouter()

@router.get("/vapid-public-key", response_model=VapidPublicKeyResponse)
async def get_vapid_public_key(current_user: User = Depends(get_current_active_user)):
    """Get the VAPID public key for push notifications."""
    if not settings.VAPID_PUBLIC_KEY:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="VAPID keys not configured on server"
        )
    return {"public_key": settings.VAPID_PUBLIC_KEY}

@router.post("/subscribe")
async def subscribe_push(
    subscription: PushSubscriptionCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """Subscribe to push notifications."""
    # Check if subscription already exists
    existing = db.query(PushSubscription).filter(
        PushSubscription.endpoint == subscription.endpoint
    ).first()
    
    if existing:
        # Update existing subscription
        existing.user_id = current_user.id
        existing.p256dh = subscription.keys.p256dh
        existing.auth = subscription.keys.auth
        db.commit()
        return {"message": "Subscription updated"}
    
    # Create new subscription
    new_sub = PushSubscription(
        user_id=current_user.id,
        endpoint=subscription.endpoint,
        p256dh=subscription.keys.p256dh,
        auth=subscription.keys.auth
    )
    db.add(new_sub)
    db.commit()
    
    return {"message": "Subscribed successfully"}

@router.delete("/unsubscribe")
async def unsubscribe_push(
    endpoint: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """Unsubscribe from push notifications."""
    db.query(PushSubscription).filter(
        PushSubscription.endpoint == endpoint
    ).delete()
    db.commit()
    
    return {"message": "Unsubscribed successfully"}

