-- 045_user_follows.sql
-- User Follow Relationships (BE-DB-006: Create migration for user_follows table)
-- Add table for user follow relationships

-- === USER FOLLOWS ===
-- Table for tracking user-to-user follow relationships
CREATE TABLE IF NOT EXISTS public.follows (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    follower_id UUID NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
    followed_id UUID NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
    
    -- Timestamps
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    
    -- Constraints
    CONSTRAINT uq_follows_follower_followed UNIQUE (follower_id, followed_id),
    CONSTRAINT chk_follows_not_self CHECK (follower_id != followed_id)
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_follows_follower_id ON public.follows(follower_id);
CREATE INDEX IF NOT EXISTS idx_follows_followed_id ON public.follows(followed_id);
CREATE INDEX IF NOT EXISTS idx_follows_created_at_desc ON public.follows(created_at DESC);

-- Comments
COMMENT ON TABLE public.follows IS 'User-to-user follow relationships';
COMMENT ON COLUMN public.follows.follower_id IS 'ID of the user who is following';
COMMENT ON COLUMN public.follows.followed_id IS 'ID of the user being followed';
COMMENT ON CONSTRAINT chk_follows_not_self ON public.follows IS 'Prevents users from following themselves';

