All files / app/api/auth/github/sync route.ts

26.78% Statements 45/168
25% Branches 4/16
100% Functions 1/1
26.78% Lines 45/168

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 2401x       1x                                                     2x 2x 2x     2x 2x 2x 2x   2x 1x 1x     1x 1x 1x 1x 1x 1x   2x 1x 1x 1x 1x 1x                                                                                                                                                                                         2x     2x 2x 2x   2x                             2x     2x                                             2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                                                     2x  
import { NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { decryptToken } from '@/lib/crypto/token-encryption';
 
const GITHUB_API_URL = 'https://api.github.com';
 
interface GitHubRepo {
  id: number;
  name: string;
  full_name: string;
  description: string | null;
  html_url: string;
  homepage: string | null;
  language: string | null;
  stargazers_count: number;
  forks_count: number;
  topics: string[];
  pushed_at: string;
  created_at: string;
  updated_at: string;
  fork: boolean;
  archived: boolean;
  private: boolean;
}
 
interface GitHubUser {
  public_repos: number;
  followers: number;
  following: number;
}
 
export async function POST() {
  try {
    const supabase = await createClient();
 
    // Verify user is authenticated
    const {
      data: { user },
      error: authError,
    } = await supabase.auth.getUser();
 
    if (authError || !user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
 
    // Get OAuth connection to get access token
    const { data: oauthConnection, error: oauthError } = await supabase
      .from('oauth_connections')
      .select('access_token_encrypted, provider_username')
      .eq('user_id', user.id)
      .eq('provider', 'github')
      .single();
 
    if (oauthError || !oauthConnection?.access_token_encrypted) {
      return NextResponse.json(
        { error: 'GitHub not connected. Please connect your GitHub account first.' },
        { status: 400 }
      );
    }
 
    const accessToken = decryptToken(oauthConnection.access_token_encrypted);
 
    // Get user's profile and developer profile
    const { data: profile } = await supabase
      .from('profiles')
      .select('id')
      .eq('user_id', user.id)
      .single();
 
    if (!profile) {
      return NextResponse.json({ error: 'Profile not found' }, { status: 404 });
    }
 
    const { data: developerProfile } = await supabase
      .from('developer_profiles')
      .select('id')
      .eq('profile_id', profile.id)
      .single();
 
    if (!developerProfile) {
      return NextResponse.json({ error: 'Developer profile not found' }, { status: 404 });
    }
 
    // Fetch user's repositories from GitHub
    const reposResponse = await fetch(
      `${GITHUB_API_URL}/user/repos?sort=pushed&per_page=100&type=owner`,
      {
        headers: {
          Authorization: `Bearer ${accessToken}`,
          Accept: 'application/vnd.github+json',
          'X-GitHub-Api-Version': '2022-11-28',
        },
      }
    );
 
    if (!reposResponse.ok) {
      if (reposResponse.status === 401) {
        // Token expired or revoked
        return NextResponse.json(
          { error: 'GitHub token expired. Please reconnect your GitHub account.' },
          { status: 401 }
        );
      }
      return NextResponse.json(
        { error: 'Failed to fetch repositories from GitHub' },
        { status: reposResponse.status }
      );
    }
 
    const repos: GitHubRepo[] = await reposResponse.json();
 
    // Fetch updated user info
    const userResponse = await fetch(`${GITHUB_API_URL}/user`, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
        Accept: 'application/vnd.github+json',
        'X-GitHub-Api-Version': '2022-11-28',
      },
    });
 
    let githubUserData: GitHubUser | null = null;
    if (userResponse.ok) {
      githubUserData = await userResponse.json();
    }
 
    // Filter out forks and archived repos, keep only public repos
    const publicRepos = repos.filter((repo) => !repo.fork && !repo.archived && !repo.private);
 
    // Calculate stats
    const totalStars = publicRepos.reduce((sum, repo) => sum + repo.stargazers_count, 0);
    const totalForks = publicRepos.reduce((sum, repo) => sum + repo.forks_count, 0);
 
    // Get primary languages
    const languageCounts: Record<string, number> = {};
    publicRepos.forEach((repo) => {
      if (repo.language) {
        languageCounts[repo.language] = (languageCounts[repo.language] || 0) + 1;
      }
    });
    const primaryLanguages = Object.entries(languageCounts)
      .sort(([, a], [, b]) => b - a)
      .slice(0, 5)
      .map(([lang]) => lang);
 
    // Get existing projects from GitHub
    const { data: existingProjects } = await supabase
      .from('code_projects')
      .select('id, github_repo_url')
      .eq('developer_profile_id', developerProfile.id)
      .eq('is_from_github', true);
 
    const existingRepoUrls = new Set(existingProjects?.map((p) => p.github_repo_url) || []);
 
    // Prepare projects for upsert (top 20 repos by stars)
    const topRepos = publicRepos
      .sort((a, b) => b.stargazers_count - a.stargazers_count)
      .slice(0, 20);
 
    const projectsToUpsert = topRepos.map((repo, index) => ({
      developer_profile_id: developerProfile.id,
      title: repo.name,
      description: repo.description || `${repo.name} - A ${repo.language || 'software'} project`,
      github_repo_url: repo.html_url,
      live_demo_url: repo.homepage || null,
      technologies: [repo.language, ...repo.topics].filter(Boolean).slice(0, 10),
      language: repo.language,
      stars: repo.stargazers_count,
      forks: repo.forks_count,
      is_from_github: true,
      is_featured: index < 3, // Feature top 3
      display_order: index,
      last_updated: repo.pushed_at,
      updated_at: new Date().toISOString(),
    }));
 
    // Upsert projects
    for (const project of projectsToUpsert) {
      if (existingRepoUrls.has(project.github_repo_url)) {
        // Update existing
        await supabase
          .from('code_projects')
          .update(project)
          .eq('developer_profile_id', developerProfile.id)
          .eq('github_repo_url', project.github_repo_url);
      } else {
        // Insert new
        await supabase.from('code_projects').insert({
          ...project,
          created_at: new Date().toISOString(),
        });
      }
    }
 
    // Update developer profile with sync info
    const { error: updateError } = await supabase
      .from('developer_profiles')
      .update({
        github_last_synced: new Date().toISOString(),
        primary_languages: primaryLanguages,
        open_source_contributions: githubUserData?.public_repos || publicRepos.length,
        github_data: {
          ...(typeof developerProfile === 'object' ? {} : {}),
          total_stars: totalStars,
          total_forks: totalForks,
          public_repos: publicRepos.length,
          followers: githubUserData?.followers || 0,
          following: githubUserData?.following || 0,
          last_synced: new Date().toISOString(),
        },
        updated_at: new Date().toISOString(),
      })
      .eq('id', developerProfile.id);
 
    if (updateError) {
      console.error('Failed to update developer profile:', updateError);
    }
 
    // Update OAuth connection last synced
    await supabase
      .from('oauth_connections')
      .update({ last_synced: new Date().toISOString() })
      .eq('user_id', user.id)
      .eq('provider', 'github');
 
    return NextResponse.json({
      success: true,
      message: 'GitHub repositories synced successfully',
      stats: {
        reposImported: topRepos.length,
        totalStars,
        totalForks,
        primaryLanguages,
      },
    });
  } catch (error) {
    console.error('GitHub sync error:', error);
    return NextResponse.json({ error: 'Failed to sync GitHub repositories' }, { status: 500 });
  }
}