/**
 * Auth middleware for Capacitor apps.
 *
 * If an Authorization: Bearer <token> header is present, copy it into the
 * request Cookie header as better-auth.session_token=<token> so Better Auth's
 * cookie-based session resolution works for all routes.
 */
export default defineEventHandler((event) => {
  const auth = getRequestHeader(event, 'authorization')
  if (!auth) return

  const match = auth.match(/^Bearer\s+(.+)$/i)
  if (!match) return

  const token = match[1]
  const existingCookie = getRequestHeader(event, 'cookie') || ''

  // Avoid duplicating if already present
  if (existingCookie.includes('better-auth.session_token=') || existingCookie.includes('better-auth.session-token=')) return

  // Set both common cookie key variants to be safe
  const safeToken = token || ''
  const cookieKeys = [
    `better-auth.session_token=${safeToken}`,
    `better-auth.session-token=${encodeURIComponent(safeToken)}`
  ]
  const cookieString = cookieKeys.join('; ')
  const newCookie = existingCookie ? `${existingCookie}; ${cookieString}` : cookieString

  // Mutate the incoming request headers before downstream handlers read them
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  ;(event.node.req.headers as any).cookie = newCookie
})
