import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import prisma from '@/lib/prisma'
import { authOptions } from '@/lib/auth'

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

    const user = await prisma.user.findUnique({
      where: { id: session.user.id },
      select: { name: true, email: true, whatsappNumber: true, telegramId: true }
    })

    return NextResponse.json({ user })
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

    const body = await req.json()
    
    // Check uniqueness if provided
    if (body.whatsappNumber) {
      const existingWa = await prisma.user.findFirst({ where: { whatsappNumber: body.whatsappNumber, id: { not: session.user.id } } })
      if (existingWa) return NextResponse.json({ error: 'Nomor WA sudah digunakan akun lain' }, { status: 400 })
    }
    
    if (body.telegramId) {
      const existingTg = await prisma.user.findFirst({ where: { telegramId: body.telegramId, id: { not: session.user.id } } })
      if (existingTg) return NextResponse.json({ error: 'Telegram ID sudah digunakan akun lain' }, { status: 400 })
    }

    await prisma.user.update({
      where: { id: session.user.id },
      data: {
        whatsappNumber: body.whatsappNumber || null,
        telegramId: body.telegramId || null
      }
    })

    return NextResponse.json({ success: true })
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}
