from app.db import database
from datetime import datetime, date

COLLECTION_NAME = "subscription_settings"

def get_subscription_settings(db: database.MongoDB) -> dict:
    return db[COLLECTION_NAME].find_one({}) or {}

def convert_dates_to_datetime(obj):
    """
    Recursively convert all datetime.date objects to datetime.datetime.
    """
    if isinstance(obj, dict):
        return {k: convert_dates_to_datetime(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [convert_dates_to_datetime(item) for item in obj]
    elif isinstance(obj, date) and not isinstance(obj, datetime):
        return datetime.combine(obj, datetime.min.time())
    return obj

def update_subscription_settings(account_id: str, data: dict, db):
    data = convert_dates_to_datetime(data)
    db["subscription_settings"].update_one(
        {"account_id": account_id},
        {"$set": data},
        upsert=True
    )
    return db["subscription_settings"].find_one({"account_id": account_id})
