import { addHTTPMiddleware } from '@pikku/core/http'
import { authBearer, cors } from '@pikku/core/middleware'
import { betterAuthStatelessSession } from '@pikku/better-auth'

addHTTPMiddleware('*', [
  cors({
    origin: ['http://localhost:7104', 'http://127.0.0.1:7104'],
    credentials: true,
  }),
  betterAuthStatelessSession({
    mapSession: (result) => ({
      userId: result.user.id,
      email: result.user.email,
      displayName: result.user.displayName ?? result.user.name ?? '',
    }),
  }),
  // External consoles (sandbox/woven-build view) can't carry the session cookie,
  // so they authenticate with `Authorization: Bearer <PIKKU_CONSOLE_TOKEN>`. The
  // CLI normally emits this alongside its session middleware, but our own global
  // session middleware above makes it step aside (pikku#754) — so add the
  // console-token bridge here or console:* RPCs 403 in the sandbox.
  authBearer({
    token: {
      secretId: 'PIKKU_CONSOLE_TOKEN',
      userSession: { userId: 'pikku-console-token' },
    },
  }),
])
