export const runtime = 'nodejs'
import { NextResponse } from 'next/server';
import { auth } from '@/auth';
import { PrismaClient } from '@/app/generated/prisma';

export async function GET() {
  const session = await auth();
  if (!session) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const email = session.user?.email as string | undefined;
  if (!email) {
    return NextResponse.json({ error: '세션 이메일을 찾을 수 없습니다' }, { status: 400 });
  }

  const prisma = new PrismaClient();
  try {
    // Admin: return all handles
    if (email === 'wsx204@naver.com') {
      const all = await prisma.handle.findMany({
        orderBy: { handle: 'asc' },
        select: { id: true, handle: true, avatar: true }
      });
      const items = all.map(h => ({
        id: h.id,
        handle: h.handle,
        createtime: new Date().toISOString(),
        is_approved: false,
        icon: h.avatar,
      }));
      return NextResponse.json({ items });
    }

    // Non-admin: handles linked to session user
    const user = await prisma.user.findFirst({ where: { email }, select: { id: true } });
    if (!user) {
      return NextResponse.json({ items: [] });
    }
    const linked = await prisma.handle.findMany({
      where: { users: { some: { id: user.id } } },
      orderBy: { handle: 'asc' },
      select: { id: true, handle: true, avatar: true }
    });
    const items = linked.map(h => ({
      id: h.id,
      handle: h.handle,
      createtime: new Date().toISOString(),
      is_approved: false,
      icon: h.avatar,
    }));
    return NextResponse.json({ items });
  } catch (e) {
    console.error('list_channel 오류:', e);
    return NextResponse.json({ error: '조회 실패' }, { status: 500 });
  } finally {
    await prisma.$disconnect();
  }
}


