-- Migration 020: Add user_id column to all_repositories table
-- This migration ensures the user_id column exists in all_repositories table

-- Check if user_id column exists, if not add it
DO $$
BEGIN
    -- Check if the column exists
    IF NOT EXISTS (
        SELECT 1 
        FROM information_schema.columns 
        WHERE table_name = 'all_repositories' 
        AND column_name = 'user_id'
        AND table_schema = 'public'
    ) THEN
        -- Add the user_id column
        ALTER TABLE all_repositories 
        ADD COLUMN user_id UUID REFERENCES users(id) ON DELETE SET NULL;
        
        RAISE NOTICE 'Added user_id column to all_repositories table';
    ELSE
        RAISE NOTICE 'user_id column already exists in all_repositories table';
    END IF;
END $$;

-- Create index for better performance if it doesn't exist
CREATE INDEX IF NOT EXISTS idx_all_repositories_user_id ON all_repositories(user_id);

-- Add comment to document the column
COMMENT ON COLUMN all_repositories.user_id IS 'References the user who owns/created this repository record';

-- Verify the column was added
DO $$
BEGIN
    IF EXISTS (
        SELECT 1 
        FROM information_schema.columns 
        WHERE table_name = 'all_repositories' 
        AND column_name = 'user_id'
        AND table_schema = 'public'
    ) THEN
        RAISE NOTICE 'SUCCESS: user_id column exists in all_repositories table';
    ELSE
        RAISE EXCEPTION 'FAILED: user_id column was not added to all_repositories table';
    END IF;
END $$;
