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

export const dynamic = 'force-dynamic'

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

  const { searchParams } = new URL(req.url)
  const roomId = searchParams.get('roomId')
  if (!roomId) return NextResponse.json({ error: 'roomId required' }, { status: 400 })

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

  // Verifikasi akses
  const room = await prisma.chatRoom.findUnique({ where: { id: roomId } })
  if (!room) return NextResponse.json({ error: 'Room tidak ditemukan' }, { status: 404 })
  if (!isAdmin && room.userId !== session.user.id) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  // Mark pesan sebagai dibaca
  if (isAdmin) {
    await prisma.$transaction([
      prisma.chatMessage.updateMany({ where: { roomId, isAdmin: false, isRead: false }, data: { isRead: true } }),
      prisma.chatRoom.update({ where: { id: roomId }, data: { unreadAdmin: 0 } }),
    ])
  } else {
    await prisma.$transaction([
      prisma.chatMessage.updateMany({ where: { roomId, isAdmin: true, isRead: false }, data: { isRead: true } }),
      prisma.chatRoom.update({ where: { id: roomId }, data: { unreadUser: 0 } }),
    ])
  }

  const messages = await prisma.chatMessage.findMany({
    where: { roomId },
    orderBy: { createdAt: 'asc' },
    take: 100,
  })

  return NextResponse.json(messages)
}

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

  const { roomId, text } = await req.json()
  if (!roomId || !text?.trim()) return NextResponse.json({ error: 'roomId dan text diperlukan' }, { status: 400 })

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

  const room = await prisma.chatRoom.findUnique({ where: { id: roomId } })
  if (!room) return NextResponse.json({ error: 'Room tidak ditemukan' }, { status: 404 })
  if (!isAdmin && room.userId !== session.user.id) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  const message = await prisma.chatMessage.create({
    data: {
      roomId,
      senderId: session.user.id,
      isAdmin,
      text: text.trim(),
    },
  })

  // Update room's lastMessage and unread counts
  await prisma.chatRoom.update({
    where: { id: roomId },
    data: {
      lastMessage: text.trim().slice(0, 100),
      updatedAt: new Date(),
      // Jika admin yang kirim → unread untuk user naik, dan sebaliknya
      unreadUser: isAdmin ? { increment: 1 } : 0,
      unreadAdmin: !isAdmin ? { increment: 1 } : 0,
    },
  })

  // Broadcast via SSE ke room-specific channel
  eventEmitter.emit(`chat_message_${roomId}`, message)

  // Jika user yang kirim → notify admin (global admin notification)
  if (!isAdmin) {
    eventEmitter.emit('admin_chat_notification', {
      roomId,
      userId: room.userId,
      text: text.trim().slice(0, 80),
    })
  }

  return NextResponse.json(message, { status: 201 })
}
