from sqlalchemy.orm import Session
from app.services.base_service import BaseService
from app.models.order import Order, OrderCard
from app.models.card import Card

class OrderService(BaseService):
    def __init__(self):
        super().__init__(Order)

    def create_order_with_cards(self, db: Session, order_data: dict, card_ids: list[int]) -> Order:
        """
        Create a new order with associated cards.
        
        Args:
            db: Database session
            order_data: Dictionary containing order details
            card_ids: List of card IDs to associate with the order
            
        Returns:
            The created Order object
        """
        # Create the order
        order = Order(**order_data)
        db.add(order)
        db.flush()  # Get the order ID
        
        # Associate cards with the order
        for card_id in card_ids:
            card = db.query(Card).filter(Card.id == card_id).first()
            if not card:
                raise ValueError(f"Card with ID {card_id} not found")
            
            order_card = OrderCard(order_id=order.id, card_id=card_id)
            db.add(order_card)
        
        db.commit()
        db.refresh(order)
        return order

    def get_orders_with_cards(self, db: Session, skip: int = 0, limit: int = 10) -> list[Order]:
        """
        Get orders with their associated cards.
        
        Args:
            db: Database session
            skip: Number of records to skip
            limit: Maximum number of records to return
            
        Returns:
            List of Order objects with their associated cards
        """
        orders = db.query(Order).offset(skip).limit(limit).all()
        
        # Eager load the cards for each order
        for order in orders:
            order.cards = db.query(Card).join(OrderCard).filter(OrderCard.order_id == order.id).all()
        
        return orders 