import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
import { db, schema } from '@/lib/db';
import { eq, and } from 'drizzle-orm';

export async function GET(request: NextRequest) {
  const session = await getSession(request.cookies.get('scriba.access_token')?.value);
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const account = await db.query.accounts.findFirst({
    where: and(eq(schema.accounts.userId, session.user.id), eq(schema.accounts.providerId, 'gitlab')),
  });

  if (!account?.accessToken) return NextResponse.json({ branches: [] });

  const { searchParams } = new URL(request.url);
  const projectPath = searchParams.get('projectPath');
  if (!projectPath) return NextResponse.json({ branches: [] });

  const res = await fetch(
    `https://gitlab.com/api/v4/projects/${encodeURIComponent(projectPath)}/repository/branches?per_page=100`,
    { headers: { 'PRIVATE-TOKEN': account.accessToken } }
  );

  if (!res.ok) return NextResponse.json({ branches: [] });
  const data = await res.json() as any[];
  return NextResponse.json({ branches: data.map((b: any) => b.name) });
}
