-- Migration 019: Add provider_name column to repository tables
-- This migration adds provider_name column to repository-related tables for multi-provider support

-- Add provider_name column to repository_commit_details table
ALTER TABLE repository_commit_details 
ADD COLUMN IF NOT EXISTS provider_name VARCHAR(50) DEFAULT 'github' NOT NULL;

-- Add provider_name column to repository_commit_files table
ALTER TABLE repository_commit_files 
ADD COLUMN IF NOT EXISTS provider_name VARCHAR(50) DEFAULT 'github' NOT NULL;

-- Add provider_name column to repository_directories table
ALTER TABLE repository_directories 
ADD COLUMN IF NOT EXISTS provider_name VARCHAR(50) DEFAULT 'github' NOT NULL;

-- Add provider_name column to repository_files table
ALTER TABLE repository_files 
ADD COLUMN IF NOT EXISTS provider_name VARCHAR(50) DEFAULT 'github' NOT NULL;

-- Add provider_name column to repository_storage table
ALTER TABLE repository_storage 
ADD COLUMN IF NOT EXISTS provider_name VARCHAR(50) DEFAULT 'github' NOT NULL;

-- Create indexes for provider_name columns for better query performance
CREATE INDEX IF NOT EXISTS idx_repository_commit_details_provider_name ON repository_commit_details(provider_name);
CREATE INDEX IF NOT EXISTS idx_repository_commit_files_provider_name ON repository_commit_files(provider_name);
CREATE INDEX IF NOT EXISTS idx_repository_directories_provider_name ON repository_directories(provider_name);
CREATE INDEX IF NOT EXISTS idx_repository_files_provider_name ON repository_files(provider_name);
CREATE INDEX IF NOT EXISTS idx_repository_storage_provider_name ON repository_storage(provider_name);

-- Add comments to document the column purpose
COMMENT ON COLUMN repository_commit_details.provider_name IS 'Repository provider (github, gitlab, bitbucket, etc.)';
COMMENT ON COLUMN repository_commit_files.provider_name IS 'Repository provider (github, gitlab, bitbucket, etc.)';
COMMENT ON COLUMN repository_directories.provider_name IS 'Repository provider (github, gitlab, bitbucket, etc.)';
COMMENT ON COLUMN repository_files.provider_name IS 'Repository provider (github, gitlab, bitbucket, etc.)';
COMMENT ON COLUMN repository_storage.provider_name IS 'Repository provider (github, gitlab, bitbucket, etc.)';

-- Update existing records to have 'github' as provider_name (if any exist without it)
UPDATE repository_commit_details 
SET provider_name = 'github' 
WHERE provider_name IS NULL OR provider_name = '';

UPDATE repository_commit_files 
SET provider_name = 'github' 
WHERE provider_name IS NULL OR provider_name = '';

UPDATE repository_directories 
SET provider_name = 'github' 
WHERE provider_name IS NULL OR provider_name = '';

UPDATE repository_files 
SET provider_name = 'github' 
WHERE provider_name IS NULL OR provider_name = '';

UPDATE repository_storage 
SET provider_name = 'github' 
WHERE provider_name IS NULL OR provider_name = '';
