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

class Vlog(Base):
    __tablename__ = "vlogs"
    
    id = Column(Integer, primary_key=True, index=True)
    author_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    title = Column(String, nullable=False)
    description = Column(Text)
    video_url = Column(String, nullable=False)
    thumbnail_url = Column(String)
    duration = Column(Integer)  # in seconds
    views_count = Column(Integer, default=0)
    replays_count = Column(Integer, default=0)
    likes_count = Column(Integer, default=0)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # Relationships
    author = relationship("User", back_populates="vlogs")
    likes = relationship("VlogLike", back_populates="vlog", cascade="all, delete-orphan")
    comments = relationship("VlogComment", back_populates="vlog", cascade="all, delete-orphan")

class VlogLike(Base):
    __tablename__ = "vlog_likes"
    
    id = Column(Integer, primary_key=True, index=True)
    vlog_id = Column(Integer, ForeignKey("vlogs.id"), nullable=False)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow)
    
    # Relationships
    vlog = relationship("Vlog", back_populates="likes")
    user = relationship("User", back_populates="vlog_likes")

    __table_args__ = (
        UniqueConstraint('vlog_id', 'user_id', name='_vlog_user_like_uc'),
    )

class VlogComment(Base):
    __tablename__ = "vlog_comments"
    
    id = Column(Integer, primary_key=True, index=True)
    vlog_id = Column(Integer, ForeignKey("vlogs.id"), nullable=False)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    content = Column(Text, nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # Relationships
    vlog = relationship("Vlog", back_populates="comments")
    user = relationship("User", back_populates="vlog_comments")

class VlogView(Base):
    __tablename__ = "vlog_views"
    
    id = Column(Integer, primary_key=True, index=True)
    vlog_id = Column(Integer, ForeignKey("vlogs.id"), nullable=False)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow)
    
    # Relationships
    vlog = relationship("Vlog")
    user = relationship("User")

    __table_args__ = (
        UniqueConstraint('vlog_id', 'user_id', name='_vlog_user_view_uc'),
    )
