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

export const dynamic = 'force-dynamic'

// GET - ambil atau buat room chat untuk user yang sedang login
// Admin: ambil semua rooms
export async function GET(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const isAdmin = session.user.role === 'ADMIN'

  if (isAdmin) {
    const rooms = await prisma.chatRoom.findMany({
      include: {
        user: { select: { id: true, name: true, email: true, image: true } },
        messages: { orderBy: { createdAt: 'desc' }, take: 1 },
      },
      orderBy: { updatedAt: 'desc' },
    })
    return NextResponse.json(rooms)
  }

  // Cari atau buat room untuk user ini
  let room = await prisma.chatRoom.findUnique({
    where: { userId: session.user.id },
    include: { user: { select: { id: true, name: true, email: true } } },
  })

  if (!room) {
    room = await prisma.chatRoom.create({
      data: { userId: session.user.id },
      include: { user: { select: { id: true, name: true, email: true } } },
    })
  }

  // Reset unread count untuk user
  await prisma.chatRoom.update({
    where: { id: room.id },
    data: { unreadUser: 0 },
  })

  return NextResponse.json(room)
}
