-- Migration 011: Support multiple GitHub accounts per user
-- This allows each user to authenticate with multiple GitHub accounts

-- Add user_id column to github_user_tokens
ALTER TABLE github_user_tokens 
ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES users(id) ON DELETE CASCADE;

-- Create indexes for faster lookups
CREATE INDEX IF NOT EXISTS idx_github_user_tokens_user_id ON github_user_tokens(user_id);
CREATE INDEX IF NOT EXISTS idx_github_user_tokens_user_github ON github_user_tokens(user_id, github_username);

-- Remove the old unique constraint on github_username (if it exists)
-- Allow multiple tokens per user, but one token per GitHub account per user
DROP INDEX IF EXISTS idx_github_user_tokens_github_username;

-- Create new unique constraint: one token per GitHub account per user
CREATE UNIQUE INDEX IF NOT EXISTS idx_github_user_tokens_unique_user_github 
ON github_user_tokens(user_id, github_username) 
WHERE user_id IS NOT NULL;

-- Add a column to track if this is the primary/default GitHub account for the user
ALTER TABLE github_user_tokens 
ADD COLUMN IF NOT EXISTS is_primary BOOLEAN DEFAULT FALSE;

-- Create index for primary account lookups
CREATE INDEX IF NOT EXISTS idx_github_user_tokens_primary ON github_user_tokens(user_id, is_primary);

-- Note: 
-- - Each user can have multiple GitHub accounts
-- - Each GitHub account can only be linked once per user
-- - One account per user can be marked as primary
-- - Repository access will be checked against all user's GitHub accounts
