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

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

  try {
    const { searchParams } = new URL(request.url);
    const handle = searchParams.get('handle');
    // 안전하게 DB에서 최신 registerCode 조회 (세션 의존 제거)
    const prisma = new PrismaClient();
    const me = await prisma.user.findFirst({ where: { email: session.user?.email ?? '' }, select: { RegisgerCode: true } });
    const registerCode = me?.RegisgerCode ?? undefined;
    console.log(`registerCode: ${registerCode} and handle: ${handle}`);
    // 이미 등록된 채널인지 사전 확인 (현재 로그인 유저 기준)
    const userRowEarly = await prisma.user.findFirst({ where: { email: session.user?.email ?? '' }, select: { id: true } });
    if (!userRowEarly) {
      await prisma.$disconnect();
      return NextResponse.json({ error: '사용자를 찾을 수 없습니다.' }, { status: 404 });
    }
    const alreadyLinkedEarly = await prisma.handle.findFirst({
      where: { handle: handle ?? '', users: { some: { id: userRowEarly.id } } },
      select: { id: true },
    });
    if (alreadyLinkedEarly) {
      await prisma.$disconnect();
      return NextResponse.json({ success: true, message: '이미 등록된 채널입니다.' }, { status: 409 });
    }
    if (!handle) {
      return NextResponse.json({ error: '핸들이 필요합니다' }, { status: 400 });
    }

    if (!registerCode) {
      return NextResponse.json({ error: 'can not find register code' }, { status: 400 });
    }

    console.log('registerCode:', registerCode);

    const upstream = await fetch('http://localhost:9556/isCodeMatch', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ handle: handle, code: registerCode })
    });

    let data: any = null;
    const text = await upstream.text();
    try {
      data = text ? JSON.parse(text) : null;
    } catch {
      data = { message: text };
    }

    console.log('data:', data);
    if (data.success) {
      if (data.foundtext) {
        if (data.foundtext == registerCode) {
          const avatarUrl = (data as any)?.avatar as string | undefined;
          // map user <-> handle (N:M)
          const email = session.user?.email ?? '';
          const userRow = await prisma.user.findFirst({ where: { email }, select: { id: true } });
          if (!userRow) {
            return NextResponse.json({ error: '사용자를 찾을 수 없습니다.' }, { status: 404 });
          }

          // ensure handle exists
          const handleRow = await prisma.handle.upsert({
            where: { handle: handle },
            update: { ...(avatarUrl ? { avatar: avatarUrl } : {}) },
            create: { handle: handle, avatar: avatarUrl ?? '' },
          });

          // avoid duplicate link
          const alreadyLinked = await prisma.handle.findFirst({
            where: { id: handleRow.id, users: { some: { id: userRow.id } } },
            select: { id: true },
          });
          if (!alreadyLinked) {
            await prisma.user.update({
              where: { id: userRow.id },
              data: { handles: { connect: { id: handleRow.id } } },
            });
          }

          await prisma.$disconnect();
          return NextResponse.json({ success: true, message: '채널 매핑 완료' }, { status: 200 });
        }
        else{
          return NextResponse.json({ error: '코드가 일치하지 않습니다.' }, { status: 400 });
        }
      } else {
        return NextResponse.json({ error: '요청 실패' }, { status: 400 });
      }
    } else {
      return NextResponse.json({ error: '요청 실패' }, { status: 400 });
    }
  

    return NextResponse.json(data ?? {}, { status: upstream.status });
  } catch (error) {
    console.error('register_channel 프록시 오류:', error);
    return NextResponse.json({ error: '업스트림 요청 실패' }, { status: 502 });
  }
}


