import { addHTTPMiddleware } from "#pikku/pikku-types.gen.js"
import { authBearer, cors } from '@pikku/core/middleware'
import { betterAuthSession } from '@pikku/better-auth'

addHTTPMiddleware('*', [
  betterAuthSession({
    mapSession: ({ user }) => ({
      userId: user.id,
      name: user.name,
      role: user.role,
      type: user.type,
    }),
  }),
  // 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 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' },
    },
  }),
])

const frontendOrigins = [
  'http://localhost:3001',
  'http://127.0.0.1:3001',
]

if (process.env.DOMAIN) {
  frontendOrigins.push(`https://${process.env.DOMAIN}`)
}

addHTTPMiddleware('*', [
  cors({
    origin: frontendOrigins,
    credentials: true,
  }),
])
