from datetime import datetime
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, UniqueConstraint
from sqlalchemy.orm import relationship
from app.database import Base

class FlashcardDeck(Base):
    __tablename__ = "flashcard_decks"
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, nullable=False)
    section_id = Column(Integer, ForeignKey("sections.id", ondelete="SET NULL"), nullable=True)
    user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
    card_count = Column(Integer, default=0)
    is_shared = Column(Integer, default=0)  # 0 = private, 1 = shared
    created_at = Column(DateTime, default=datetime.utcnow)
    deleted_at = Column(DateTime, nullable=True)
    cards = relationship("Flashcard", back_populates="deck", cascade="all, delete-orphan")
    ratings = relationship("FlashcardDeckRating", back_populates="deck", cascade="all, delete-orphan")
    user = relationship("User")


class FlashcardDeckRating(Base):
    __tablename__ = "flashcard_deck_ratings"
    __table_args__ = (UniqueConstraint("user_id", "deck_id", name="uq_deck_rating_user"),)
    id = Column(Integer, primary_key=True, index=True)
    deck_id = Column(Integer, ForeignKey("flashcard_decks.id", ondelete="CASCADE"), nullable=False)
    user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
    rating = Column(Integer, nullable=False)  # 1-5
    created_at = Column(DateTime, default=datetime.utcnow)
    deck = relationship("FlashcardDeck", back_populates="ratings")

class Flashcard(Base):
    __tablename__ = "flashcards"
    id = Column(Integer, primary_key=True, index=True)
    deck_id = Column(Integer, ForeignKey("flashcard_decks.id", ondelete="CASCADE"), nullable=False)
    front = Column(Text, nullable=False)
    back = Column(Text, nullable=False)
    page_reference = Column(Integer, nullable=True)
    image_path = Column(String, nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    deck = relationship("FlashcardDeck", back_populates="cards")
