-- Migration 013: Add user_id to github_user_tokens table
-- This fixes the GitHub OAuth callback error: "Cannot read properties of undefined (reading 'count')"

-- Add user_id column to github_user_tokens table
ALTER TABLE github_user_tokens 
ADD COLUMN IF NOT EXISTS user_id UUID;

-- Add is_primary column to support multiple GitHub accounts per user
ALTER TABLE github_user_tokens 
ADD COLUMN IF NOT EXISTS is_primary BOOLEAN DEFAULT false;

-- Create index for better performance
CREATE INDEX IF NOT EXISTS idx_github_user_tokens_user_id ON github_user_tokens(user_id);

-- Add unique constraint to prevent duplicate primary accounts per user
CREATE UNIQUE INDEX IF NOT EXISTS idx_github_user_tokens_user_primary 
ON github_user_tokens(user_id, github_username) 
WHERE is_primary = true;

-- Update existing records to set a default user_id if needed (optional)
-- UPDATE github_user_tokens SET user_id = uuid_generate_v4() WHERE user_id IS NULL;
