from sqlalchemy import Column, String, DateTime, Text, Integer, ForeignKey
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
import uuid

from ..core.database import Base

class BookCategory(Base):
    """서적 소분류 테이블 (서적 내 문서 그룹화)"""
    __tablename__ = "book_categories"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    book_id = Column(UUID(as_uuid=True), ForeignKey('books.id', ondelete='CASCADE'), nullable=False, index=True)
    name = Column(String(200), nullable=False)  # 소분류 이름 (예: "Chapter 1", "설계 기준", "계산서")
    description = Column(Text, nullable=True)  # 소분류 설명
    sort_order = Column(Integer, default=0)  # 소분류 정렬 순서
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    # 관계
    book = relationship("Book", back_populates="categories")
    documents = relationship("Document", back_populates="category", cascade="all, delete-orphan")

    def __repr__(self):
        return f"<BookCategory(name='{self.name}', book='{self.book.title if self.book else None}')>"
