from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, Integer, JSON
from sqlalchemy.orm import Mapped, mapped_column, relationship
from typing import TYPE_CHECKING

from app.core.database import Base

if TYPE_CHECKING:
    from app.models.user import User
    from app.models.shop import ShopItem
    from app.models.marathon import Marathon
    from app.models.assignment import Assignment


class ConsumableUsage(Base):
    __tablename__ = "consumable_usages"

    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
    item_id: Mapped[int] = mapped_column(ForeignKey("shop_items.id", ondelete="CASCADE"), nullable=False)
    marathon_id: Mapped[int | None] = mapped_column(ForeignKey("marathons.id", ondelete="CASCADE"), nullable=True)
    assignment_id: Mapped[int | None] = mapped_column(ForeignKey("assignments.id", ondelete="CASCADE"), nullable=True)
    used_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
    effect_data: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    # Relationships
    user: Mapped["User"] = relationship("User")
    item: Mapped["ShopItem"] = relationship("ShopItem")
    marathon: Mapped["Marathon | None"] = relationship("Marathon")
    assignment: Mapped["Assignment | None"] = relationship("Assignment")
