-- 노트용 하이라이트 테이블 생성
CREATE TABLE note_highlights (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    note_id UUID NOT NULL REFERENCES notes_documents(id) ON DELETE CASCADE,
    start_offset INTEGER NOT NULL,
    end_offset INTEGER NOT NULL,
    selected_text TEXT NOT NULL,
    highlight_color VARCHAR(50) NOT NULL DEFAULT '#FFFF00',
    highlight_type VARCHAR(50) NOT NULL DEFAULT 'highlight',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    created_by VARCHAR(100) NOT NULL
);

-- 노트용 메모 테이블 생성
CREATE TABLE note_notes (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    note_id UUID NOT NULL REFERENCES notes_documents(id) ON DELETE CASCADE,
    highlight_id UUID REFERENCES note_highlights(id) ON DELETE CASCADE,
    content TEXT NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    created_by VARCHAR(100) NOT NULL
);

-- 인덱스 생성
CREATE INDEX ix_note_highlights_note_id ON note_highlights (note_id);
CREATE INDEX ix_note_highlights_created_by ON note_highlights (created_by);
CREATE INDEX ix_note_notes_note_id ON note_notes (note_id);
CREATE INDEX ix_note_notes_highlight_id ON note_notes (highlight_id);
CREATE INDEX ix_note_notes_created_by ON note_notes (created_by);

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

CREATE TRIGGER update_note_highlights_updated_at 
    BEFORE UPDATE ON note_highlights 
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

CREATE TRIGGER update_note_notes_updated_at 
    BEFORE UPDATE ON note_notes 
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
