from sqlalchemy import Column, String, Text, DateTime, ForeignKey
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from pydantic import BaseModel
from typing import Optional
from datetime import datetime
import uuid

from ..core.database import Base

class NoteNote(Base):
    """노트의 메모 모델 (노트 안의 하이라이트에 대한 메모)"""
    __tablename__ = "note_notes"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    note_id = Column(UUID(as_uuid=True), ForeignKey("notes_documents.id", ondelete="CASCADE"), nullable=False)
    highlight_id = Column(UUID(as_uuid=True), ForeignKey("note_highlights.id", ondelete="CASCADE"), nullable=True)
    content = Column(Text, nullable=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    created_by = Column(String(100), nullable=False)

    # 관계
    note = relationship("NoteDocument", back_populates="notes")
    highlight = relationship("NoteHighlight", back_populates="notes")

# Pydantic 모델들
class NoteNoteBase(BaseModel):
    note_id: str
    highlight_id: Optional[str] = None
    content: str

class NoteNoteCreate(NoteNoteBase):
    pass

class NoteNoteUpdate(BaseModel):
    content: Optional[str] = None

class NoteNoteResponse(NoteNoteBase):
    id: str
    created_at: datetime
    updated_at: datetime
    created_by: str

    class Config:
        from_attributes = True

    @classmethod
    def from_orm(cls, obj):
        return cls(
            id=str(obj.id),
            note_id=str(obj.note_id),
            highlight_id=str(obj.highlight_id) if obj.highlight_id else None,
            content=obj.content,
            created_at=obj.created_at,
            updated_at=obj.updated_at,
            created_by=obj.created_by
        )
