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

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

  const userId = parseInt((session.user as { id: string }).id)
  if (isNaN(userId)) return NextResponse.json({ ok: false }, { status: 400 })

  const forwarded = req.headers.get('x-forwarded-for')
  const ip = forwarded ? forwarded.split(',')[0].trim() : (req.headers.get('x-real-ip') ?? undefined)

  const existing = await prisma.activeSession.findUnique({ where: { userId } })

  await prisma.activeSession.upsert({
    where: { userId },
    create: { userId, ip: ip ?? null, lastSeen: new Date() },
    update: { lastSeen: new Date(), ip: ip ?? null },
  })

  if (!existing) {
    await prisma.sessionLog.create({
      data: { userId, ip: ip ?? null },
    })
  }

  return NextResponse.json({ ok: true })
}
