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({ connected: false, groups: [] });

  const res = await fetch(
    'https://gitlab.com/api/v4/groups?per_page=100&min_access_level=20&order_by=name',
    { headers: { 'PRIVATE-TOKEN': account.accessToken } }
  );

  if (!res.ok) return NextResponse.json({ connected: true, groups: [] });

  const data = await res.json() as any[];
  const groups = data.map((g: any) => ({
    id: g.id,
    name: g.name,
    path: g.path,
    fullPath: g.full_path,
    avatarUrl: g.avatar_url,
  }));

  return NextResponse.json({ connected: true, groups });
}
