-- Migration: Create room_members table
-- Description: Members of chat rooms

CREATE TABLE IF NOT EXISTS room_members (
    id BIGSERIAL PRIMARY KEY,
    room_id BIGINT NOT NULL,
    user_id BIGINT NOT NULL,
    role VARCHAR(50) NOT NULL DEFAULT 'member', -- 'admin', 'moderator', 'member'
    joined_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    last_read_at TIMESTAMP WITH TIME ZONE,
    is_muted BOOLEAN DEFAULT false,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP WITH TIME ZONE,
    
    CONSTRAINT fk_room_members_room_id FOREIGN KEY (room_id) REFERENCES rooms(id) ON DELETE CASCADE,
    CONSTRAINT fk_room_members_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    CONSTRAINT unique_room_member UNIQUE (room_id, user_id)
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_room_members_room_id ON room_members(room_id);
CREATE INDEX IF NOT EXISTS idx_room_members_user_id ON room_members(user_id);
CREATE INDEX IF NOT EXISTS idx_room_members_role ON room_members(role);
CREATE INDEX IF NOT EXISTS idx_room_members_deleted_at ON room_members(deleted_at);

-- Comments
COMMENT ON TABLE room_members IS 'Members of chat rooms with roles and permissions';
COMMENT ON COLUMN room_members.role IS 'Member role: admin, moderator, or member';
COMMENT ON COLUMN room_members.last_read_at IS 'Timestamp of last message read by user';
COMMENT ON COLUMN room_members.is_muted IS 'Whether notifications are muted for this user';

