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, repos: [] });

  const { searchParams } = new URL(request.url);
  const page = searchParams.get('page') ?? '1';
  const q = searchParams.get('q') ?? '';
  const group = searchParams.get('group') ?? '';

  const headers = { 'PRIVATE-TOKEN': account.accessToken };

  let apiUrl: string;
  if (group) {
    const base = `https://gitlab.com/api/v4/groups/${encodeURIComponent(group)}/projects?per_page=50&page=${page}&order_by=last_activity_at&sort=desc&include_subgroups=true`;
    apiUrl = q ? `${base}&search=${encodeURIComponent(q)}` : base;
  } else {
    const base = `https://gitlab.com/api/v4/projects?membership=true&per_page=50&page=${page}&order_by=last_activity_at&sort=desc`;
    apiUrl = q ? `${base}&search=${encodeURIComponent(q)}` : base;
  }

  const res = await fetch(apiUrl, { headers });
  if (!res.ok) return NextResponse.json({ connected: false, repos: [] });

  const data = await res.json() as any[];
  const repos = data.map((r: any) => ({
    id: r.id,
    name: r.name,
    pathWithNamespace: r.path_with_namespace,
    description: r.description,
    visibility: r.visibility,
    language: null,
    defaultBranch: r.default_branch || 'main',
    webUrl: r.web_url,
    lastActivityAt: r.last_activity_at,
  }));

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