-- 046_user_blocks.sql
-- User Block Relationships (BE-DB-007: Create migration for user_blocks table)
-- Add table for user block relationships

-- === USER BLOCKS ===
-- Table for tracking user-to-user block relationships
CREATE TABLE IF NOT EXISTS public.user_blocks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    blocker_id UUID NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
    blocked_id UUID NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
    
    -- Optional reason for blocking
    reason VARCHAR(255),
    
    -- Timestamps
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    
    -- Constraints
    CONSTRAINT uq_user_blocks_blocker_blocked UNIQUE (blocker_id, blocked_id),
    CONSTRAINT chk_user_blocks_not_self CHECK (blocker_id != blocked_id)
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocker_id ON public.user_blocks(blocker_id);
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocked_id ON public.user_blocks(blocked_id);
CREATE INDEX IF NOT EXISTS idx_user_blocks_created_at_desc ON public.user_blocks(created_at DESC);

-- Comments
COMMENT ON TABLE public.user_blocks IS 'User-to-user block relationships';
COMMENT ON COLUMN public.user_blocks.blocker_id IS 'ID of the user who is blocking';
COMMENT ON COLUMN public.user_blocks.blocked_id IS 'ID of the user being blocked';
COMMENT ON COLUMN public.user_blocks.reason IS 'Optional reason for blocking';
COMMENT ON CONSTRAINT chk_user_blocks_not_self ON public.user_blocks IS 'Prevents users from blocking themselves';

