import { prisma } from '@/lib/db'
import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { clearSessionCookie } from '@/lib/auth/session'

/**
 * Sign-out revokes the session row as well as clearing the cookie. Clearing the cookie
 * alone would leave a still-valid token in anyone's hands who had captured it.
 */
export const POST = apiRoute({}, async ({ user, request }) => {
  await prisma.session.update({
    where: { id: user.sessionId },
    data: { revokedAt: new Date() },
  })
  await clearSessionCookie()
  await writeAudit({
    action: AUDIT_ACTIONS.logout,
    entity: 'session',
    entityId: user.sessionId,
    user,
    request,
  })
  return { signedOut: true }
})
