import { NextRequest } from 'next/server';
import { getSession } from '@/lib/auth';
import { createResponse, handleApiError } from '@/lib/api';

export async function GET(req: NextRequest) {
  try {
    const session = await getSession();
    const search = req.nextUrl.searchParams.get('search') ?? '';

    const result = await fetch(`https://api.vercel.com/v1/integrations/search-repo?query=${search}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${session?.user.vercelAccessToken}`,
      },
    });

    const data = await result.json();
    return createResponse(200, 'Repositories retrieved', { data: data.repos });
  } catch (error) {
    return handleApiError(error);
  }
}
