# Push notifications
from fastapi import APIRouter, Depends, HTTPException, status, Body
import pymongo

import app.config as config
from app.models import User, HTTPError, PushSubscription
from app.routes.utils import get_current_user

# Database setup
client = pymongo.MongoClient(config.MONGODB_URL, username=config.MONGODB_USERNAME, password=config.MONGODB_PASSWORD)
db = client[config.MONGODB_DATABASE]

users_collection = db["users"]

push_router = APIRouter(
    tags=["Push"]
)

@push_router.post(
    path="/push/subscribe",
    responses={401: {"model": HTTPError}}
)
async def subscribe(subscription: PushSubscription, current_user: User = Depends(get_current_user)):
    # Convert the subscription to a JSON string
    subscription_str = subscription.model_dump_json()

    # Check if the subscription is already in the database
    if users_collection.find_one({"push_subscriptions": subscription_str}):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Subscription already exists"
        )
    
    # Check if already has a subscription
    if current_user.push_subscriptions:
        # Add another subscription
        users_collection.update_one(
            {"username": current_user.username},
            {"$push": {"push_subscriptions": subscription_str}}
        )
    else:
        # Add the subscription
        users_collection.update_one(
            {"username": current_user.username},
            {"$set": {"push_subscriptions": [subscription_str]}}
        )

    return {
        "message": "Push subscription successful"
    }
