-- 문서 링크 테이블 생성
CREATE TABLE document_links (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    source_document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
    target_document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
    selected_text TEXT NOT NULL,
    start_offset INTEGER NOT NULL,
    end_offset INTEGER NOT NULL,
    link_text VARCHAR(500),
    description TEXT,
    created_by UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE
);

-- 인덱스 생성
CREATE INDEX idx_document_links_source_document_id ON document_links(source_document_id);
CREATE INDEX idx_document_links_target_document_id ON document_links(target_document_id);
CREATE INDEX idx_document_links_created_by ON document_links(created_by);
CREATE INDEX idx_document_links_start_offset ON document_links(start_offset);

-- 업데이트 트리거 생성
CREATE OR REPLACE FUNCTION update_document_links_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_update_document_links_updated_at
    BEFORE UPDATE ON document_links
    FOR EACH ROW
    EXECUTE FUNCTION update_document_links_updated_at();
