from pymongo.database import Database
from pymongo.errors import PyMongoError
import logging

logger = logging.getLogger("DBManager")
logger.setLevel(logging.INFO)

class MongoDBManager:
    def __init__(self, db: Database):
        self.db = db  # Use the existing DB instance
        logger.info("Using injected MongoDB instance")

    def get_user_portfolio(self, user_id: str, collection_name: str = "zerodha_portfolios") -> list:
        try:
            collection = self.db[collection_name]
            portfolio = collection.find_one({"user_id": user_id}, {"_id": 0, "holdings": 1})
            return portfolio.get("holdings", []) if portfolio else []
        except PyMongoError as e:
            logger.error(f"Error fetching portfolio: {e}")
            return []

    def save_signal(self, signal_data: dict, collection_name: str = "trading_signals"):
        try:
            collection = self.db[collection_name]
            result = collection.insert_one(signal_data)
            logger.info(f"Signal saved with ID: {result.inserted_id}")
            return result.inserted_id
        except PyMongoError as e:
            logger.error(f"Error saving signal: {e}")

    def save_execution_log(self, order_data: dict, collection_name: str = "order_executions"):
        try:
            collection = self.db[collection_name]
            result = collection.insert_one(order_data)
            logger.info(f"Execution log saved for order: {order_data.get('order_id')}")
            return result.inserted_id
        except PyMongoError as e:
            logger.error(f"Error saving execution log: {e}")
