-- 서적 테이블 및 관계 추가
-- 2025-08-22: 서적 그룹화 기능 추가

-- 서적 테이블 생성
CREATE TABLE IF NOT EXISTS books (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    title VARCHAR(500) NOT NULL,
    author VARCHAR(200),
    publisher VARCHAR(200),
    isbn VARCHAR(20) UNIQUE,
    description TEXT,
    language VARCHAR(10) DEFAULT 'ko',
    total_pages INTEGER DEFAULT 0,
    cover_image_path VARCHAR(500),
    is_public BOOLEAN DEFAULT true,
    tags VARCHAR(1000),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE
);

-- 인덱스 생성
CREATE INDEX IF NOT EXISTS idx_books_title ON books(title);
CREATE INDEX IF NOT EXISTS idx_books_author ON books(author);
CREATE INDEX IF NOT EXISTS idx_books_created_at ON books(created_at);

-- documents 테이블에 book_id 컬럼 추가
ALTER TABLE documents ADD COLUMN IF NOT EXISTS book_id UUID;

-- 외래키 제약조건 추가
ALTER TABLE documents ADD CONSTRAINT IF NOT EXISTS fk_documents_book_id 
    FOREIGN KEY (book_id) REFERENCES books(id) ON DELETE SET NULL;

-- book_id 인덱스 생성
CREATE INDEX IF NOT EXISTS idx_documents_book_id ON documents(book_id);

-- 업데이트 트리거 함수 생성 (updated_at 자동 업데이트)
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ language 'plpgsql';

-- books 테이블에 업데이트 트리거 추가
DROP TRIGGER IF EXISTS update_books_updated_at ON books;
CREATE TRIGGER update_books_updated_at
    BEFORE UPDATE ON books
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();
