import { getServerSession } from 'next-auth';
import { authOptions, getUserGuilds, isAdmin } from '@/lib/auth';
import { getBotGuilds } from '@/lib/discord';
import { NextResponse } from 'next/server';

export async function GET() {
  const session = await getServerSession(authOptions) as any;
  if (!session) return NextResponse.json([], { status: 401 });

  const [userGuilds, botGuilds] = await Promise.all([
    getUserGuilds(session.accessToken),
    getBotGuilds()
  ]);

  const botGuildIds = new Set(botGuilds.map((g: any) => g.id));

  const filtered = userGuilds.filter((g: any) => {
    if (!botGuildIds.has(g.id)) return false;
    const hasAdmin = (g.permissions & 0x8) === 0x8;
    return hasAdmin || isAdmin(session.user.id);
  });

  return NextResponse.json(filtered);
}
