"""Notification routes — FCM token registration and reminder settings."""
from fastapi import APIRouter, HTTPException
from db import get_database
from pydantic import BaseModel
from typing import Optional
from bson import ObjectId
from bson.errors import InvalidId
from datetime import datetime

router = APIRouter()


class FcmTokenRequest(BaseModel):
    userId: str
    fcmToken: str


class ReminderSettingsRequest(BaseModel):
    time: Optional[str] = None      # "HH:MM" in 24-hour format
    enabled: bool
    timezone: Optional[str] = None  # IANA timezone, e.g. "Asia/Kolkata"


@router.post("/fcm-token", response_model=dict)
async def register_fcm_token(body: FcmTokenRequest):
    """
    Register (or refresh) an FCM device token for a user.
    Stores unique tokens per user — duplicate tokens are ignored.
    """
    db = get_database()

    try:
        user_oid = ObjectId(body.userId)
    except InvalidId:
        raise HTTPException(status_code=400, detail="Invalid user ID")

    user = db.users.find_one({"_id": user_oid})
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    # Add token to set (avoid duplicates)
    db.users.update_one(
        {"_id": user_oid},
        {
            "$addToSet": {"fcmTokens": body.fcmToken},
            "$set": {"updatedAt": datetime.utcnow()},
        }
    )
    return {"message": "FCM token registered"}


@router.put("/reminder/{user_id}", response_model=dict)
async def update_reminder(user_id: str, settings: ReminderSettingsRequest):
    """
    Save or update daily reminder settings for a user.
    """
    db = get_database()

    try:
        user_oid = ObjectId(user_id)
    except InvalidId:
        raise HTTPException(status_code=400, detail="Invalid user ID")

    user = db.users.find_one({"_id": user_oid})
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    reminder_update: dict = {"reminder.enabled": settings.enabled}
    if settings.time is not None:
        reminder_update["reminder.time"] = settings.time
    if settings.timezone is not None:
        reminder_update["reminder.timezone"] = settings.timezone

    db.users.update_one(
        {"_id": user_oid},
        {"$set": {**reminder_update, "updatedAt": datetime.utcnow()}}
    )
    return {"message": "Reminder settings updated"}
