import { createHash } from 'crypto'
import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'
import { prisma } from '@/lib/prisma'
import { sessionOptions, type SessionData } from '@/lib/session'

// Probeert eerst Bearer-token (REST/MCP), valt terug op iron-session
// cookie (browser fetches vanuit ingelogde sessie). Cookie-pad is bewust
// voor Solo Paneel-mutations die anders via Server Action zouden gaan —
// maar Server Actions triggeren een page-refresh die SSE-streams sluit.
export async function authenticateApiRequest(request: Request) {
  const authHeader = request.headers.get('Authorization')

  if (authHeader?.startsWith('Bearer ')) {
    const token = authHeader.slice(7)
    const tokenHash = createHash('sha256').update(token).digest('hex')

    const apiToken = await prisma.apiToken.findUnique({
      where: { token_hash: tokenHash },
      include: { user: true },
    })

    if (!apiToken || apiToken.revoked_at) {
      return { error: 'Unauthorized', status: 401 as const }
    }
    return { userId: apiToken.user_id, isDemo: apiToken.user.is_demo }
  }

  // Geen Bearer — probeer iron-session cookie
  try {
    const session = await getIronSession<SessionData>(await cookies(), sessionOptions)
    if (session.userId) {
      return { userId: session.userId, isDemo: session.isDemo ?? false }
    }
  } catch {
    // cookies() outside of request-scope kan throwen — laat door naar 401
  }

  return { error: 'Unauthorized', status: 401 as const }
}
