-- Migration 001: Add GitHub Integration Tables (PostgreSQL Only)
-- This migration adds support for GitHub repository integration

-- Create table for GitHub repositories
CREATE TABLE IF NOT EXISTS all_repositories (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  template_id UUID,
  repository_url VARCHAR(500) NOT NULL,
  repository_name VARCHAR(200) NOT NULL,
  owner_name VARCHAR(100) NOT NULL,
  provider_name VARCHAR(50) DEFAULT 'github' NOT NULL,
  branch_name VARCHAR(100) DEFAULT 'main',
  is_public BOOLEAN DEFAULT true,
  requires_auth BOOLEAN DEFAULT false,
  last_synced_at TIMESTAMP,
  sync_status VARCHAR(50) DEFAULT 'pending',
  metadata JSONB,
  codebase_analysis JSONB,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);


-- Create indexes for better performance
-- Only create template_id index if the column exists (it gets removed in migration 010)
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.columns 
              WHERE table_name = 'all_repositories' AND column_name = 'template_id') THEN
        CREATE INDEX IF NOT EXISTS idx_github_repos_template_id ON all_repositories(template_id);
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_github_repos_owner_name ON all_repositories(owner_name);
CREATE INDEX IF NOT EXISTS idx_all_repos_provider_name ON all_repositories(provider_name);
-- Note: feature_codebase_mappings table indexes will be created when that table is added

-- Add foreign key constraint if templates table exists and template_id column exists
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'templates') 
       AND EXISTS (SELECT 1 FROM information_schema.columns 
                  WHERE table_name = 'all_repositories' AND column_name = 'template_id') THEN
        ALTER TABLE all_repositories ADD CONSTRAINT fk_all_repositories_template_id 
            FOREIGN KEY (template_id) REFERENCES templates(id) ON DELETE CASCADE;
    END IF;
END $$;

-- Add trigger to update timestamp
CREATE TRIGGER update_github_repos_updated_at BEFORE UPDATE ON all_repositories
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- =============================================
-- GitHub OAuth Tables
-- =============================================

-- Create table to store GitHub OAuth tokens
CREATE TABLE IF NOT EXISTS github_user_tokens (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  access_token TEXT NOT NULL,
  github_username VARCHAR(100) NOT NULL,
  github_user_id INTEGER NOT NULL,
  scopes JSONB,
  expires_at TIMESTAMP,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

-- Create index for faster lookups
CREATE INDEX IF NOT EXISTS idx_github_user_tokens_github_username ON github_user_tokens(github_username);
