-- Migration: Add user blocks table
-- Date: 2026-01-28
-- Description: Allows users to block other users from sending messages

-- Create user_blocks table
CREATE TABLE IF NOT EXISTS user_blocks (
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    blocked_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    reason TEXT,  -- optional reason for blocking

    -- Prevent duplicate blocks
    UNIQUE(user_id, blocked_user_id),

    -- Prevent self-blocking
    CHECK (user_id != blocked_user_id)
);

-- Index for efficient lookups
CREATE INDEX IF NOT EXISTS idx_user_blocks_user_id ON user_blocks(user_id);
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocked_user_id ON user_blocks(blocked_user_id);

-- Comments for documentation
COMMENT ON TABLE user_blocks IS 'Stores user blocking relationships - blocked users cannot send messages';
COMMENT ON COLUMN user_blocks.user_id IS 'User who created the block';
COMMENT ON COLUMN user_blocks.blocked_user_id IS 'User who is blocked';
COMMENT ON COLUMN user_blocks.reason IS 'Optional reason for blocking';

-- Grant permissions
GRANT ALL ON TABLE user_blocks TO nordabiz_app;
GRANT USAGE, SELECT ON SEQUENCE user_blocks_id_seq TO nordabiz_app;
