import { NextRequest, NextResponse } from 'next/server' import { createServerSupabaseClient } from '@/lib/supabase' export async function GET(request: NextRequest) { try { const supabase = createServerSupabaseClient() // Get current user session (handle both auth header and session) const authHeader = request.headers.get('authorization') let user try { if (authHeader) { // Handle if there's an auth header const { data: { user: authUser }, error: authError } = await supabase.auth.getUser(authHeader.replace('Bearer ', '')) if (!authError) user = authUser } else { // Try to get user from session const { data: { user: sessionUser }, error: sessionError } = await supabase.auth.getUser() if (!sessionError) user = sessionUser } } catch (e) { // Ignore auth errors for now } if (!user) { return NextResponse.json( { error: 'Authentication required' }, { status: 401 } ) } // Get user's GitHub integrations from profile const { data: profile } = await supabase .from('profiles') .select('github_integrations') .eq('id', user.id) .single() const githubIntegrations = profile?.github_integrations || {} // Find the first integration to get access token and username const integrationKeys = Object.keys(githubIntegrations) if (integrationKeys.length === 0) { return NextResponse.json( { error: 'No GitHub integration found' }, { status: 404 } ) } // Use the first integration to get access token and username const firstIntegration = githubIntegrations[integrationKeys[0]] const accessToken = firstIntegration.access_token const githubUsername = firstIntegration.github_username if (!accessToken || !githubUsername) { return NextResponse.json( { error: 'Invalid GitHub integration data' }, { status: 400 } ) } // Fetch repositories from GitHub const reposResponse = await fetch('https://api.github.com/user/repos?type=all&sort=updated&per_page=100', { headers: { 'Authorization': `Bearer ${accessToken}`, 'Accept': 'application/vnd.github.v3+json', }, }) if (!reposResponse.ok) { return NextResponse.json( { error: 'Failed to fetch repositories from GitHub' }, { status: 500 } ) } const repositories = await reposResponse.json() const formattedRepos = repositories.slice(0, 50).map((repo: any) => ({ id: repo.id, name: repo.name, full_name: repo.full_name, private: repo.private, updated_at: repo.updated_at, description: repo.description })) return NextResponse.json({ repositories: formattedRepos, accessToken, githubUsername }) } catch (error) { console.error('Error fetching GitHub repositories:', error) return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ) } }