"""
할일관리 시스템 모델
"""
from sqlalchemy import Column, String, DateTime, Text, Boolean, Integer, ForeignKey
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from datetime import datetime
import uuid

from ..core.database import Base


class TodoItem(Base):
    """할일 아이템"""
    __tablename__ = "todo_items"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    user_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
    
    # 기본 정보
    content = Column(Text, nullable=False)  # 할일 내용
    status = Column(String(20), nullable=False, default="draft")  # draft, scheduled, active, completed, delayed
    photo_url = Column(String(500), nullable=True)  # 첨부 사진 URL
    
    # 시간 관리
    created_at = Column(DateTime(timezone=True), nullable=False, default=datetime.utcnow)
    start_date = Column(DateTime(timezone=True), nullable=True)  # 시작 예정일
    estimated_minutes = Column(Integer, nullable=True)  # 예상 소요시간 (분)
    completed_at = Column(DateTime(timezone=True), nullable=True)
    delayed_until = Column(DateTime(timezone=True), nullable=True)  # 지연된 경우 새로운 시작일
    
    # 분할 관리
    parent_id = Column(UUID(as_uuid=True), ForeignKey("todo_items.id"), nullable=True)  # 분할된 할일의 부모
    split_order = Column(Integer, nullable=True)  # 분할 순서
    
    # 관계
    user = relationship("User", back_populates="todo_items")
    comments = relationship("TodoComment", back_populates="todo_item", cascade="all, delete-orphan")
    
    # 자기 참조 관계 (분할된 할일들)
    subtasks = relationship("TodoItem", backref="parent_task", remote_side=[id])

    def __repr__(self):
        return f"<TodoItem(id={self.id}, content='{self.content[:50]}...', status='{self.status}')>"


class TodoComment(Base):
    """할일 댓글/메모"""
    __tablename__ = "todo_comments"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    todo_item_id = Column(UUID(as_uuid=True), ForeignKey("todo_items.id"), nullable=False)
    user_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
    
    content = Column(Text, nullable=False)
    created_at = Column(DateTime(timezone=True), nullable=False, default=datetime.utcnow)
    updated_at = Column(DateTime(timezone=True), nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 관계
    todo_item = relationship("TodoItem", back_populates="comments")
    user = relationship("User")

    def __repr__(self):
        return f"<TodoComment(id={self.id}, content='{self.content[:30]}...')>"
