-- V9: Add notification and private message support

-- Notification table: system/reply/like alerts to a user
CREATE TABLE IF NOT EXISTS notification (
    id          INT PRIMARY KEY AUTO_INCREMENT,
    user_id     INT NOT NULL,           -- receiver
    from_user_id INT,                   -- sender (NULL for system notifications)
    type        VARCHAR(50) NOT NULL,   -- 'reply', 'like', 'system'
    title       VARCHAR(200),
    content     TEXT,
    related_id  INT,                    -- e.g. discussion_id or post_id
    related_type VARCHAR(50),           -- 'discussion', 'post'
    is_read     BOOLEAN DEFAULT FALSE,
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_notification_user ON notification(user_id);
CREATE INDEX IF NOT EXISTS idx_notification_user_unread ON notification(user_id, is_read);

-- Message table: private messages between users
CREATE TABLE IF NOT EXISTS message (
    id              INT PRIMARY KEY AUTO_INCREMENT,
    sender_id       INT NOT NULL,
    receiver_id     INT NOT NULL,
    content         TEXT NOT NULL,
    is_read         BOOLEAN DEFAULT FALSE,
    create_time     DATETIME DEFAULT CURRENT_TIMESTAMP,
    conversation_id VARCHAR(50) NOT NULL  -- format: min_max of user IDs
);

CREATE INDEX IF NOT EXISTS idx_message_receiver ON message(receiver_id);
CREATE INDEX IF NOT EXISTS idx_message_conversation ON message(conversation_id, create_time);
CREATE INDEX IF NOT EXISTS idx_message_receiver_unread ON message(receiver_id, is_read);
