/**
 * OAuth 2.0 Authorization Server routes (wave-12).
 *
 * Top-level routes (mounted at /oauth in index.ts — NOT under /api):
 *   GET/POST /oauth/authorize  — consent endpoint (requires user session)
 *   POST /oauth/token          — code exchange + refresh (server-to-server, no session)
 *   POST /oauth/revoke         — token revocation (no session)
 *
 * API routes (mounted under /api/oauth in routes/index.ts):
 *   GET  /api/oauth/connections
 *   DELETE /api/oauth/connections/:clientId
 *
 * Admin routes (mounted under /api/admin/oauth in routes/index.ts):
 *   GET  /api/admin/oauth/clients
 *   POST /api/admin/oauth/clients
 *   PATCH /api/admin/oauth/clients/:id
 */
import { Hono } from 'hono'
import { authMiddleware } from '../../middleware/auth'
import { adminAuthMiddleware } from '../../middleware/admin-auth'
import { requireAdminSession } from '@zync/auth'
import { authorizeRoute } from './authorize'
import { tokenRoute } from './token'
import { revokeRoute } from './revoke'
import { connectionsRoute } from './connections'
import { adminOAuthClientsRoute } from './admin-clients'
import type { AppEnv } from '../../types'

// ── AS router (top-level /oauth) ───────────────────────────────────────────────
// IMPORTANT: authMiddleware is applied only to /authorize (user session required).
// /token and /revoke are server-to-server and must NOT require a user session.

const oauthRouter = new Hono<AppEnv>()

// /oauth/authorize requires user session
const authorizeProtected = new Hono<AppEnv>()
authorizeProtected.use('*', authMiddleware)
authorizeProtected.route('/', authorizeRoute)
oauthRouter.route('/', authorizeProtected)

// /oauth/token and /oauth/revoke — no session middleware
oauthRouter.route('/', tokenRoute)
oauthRouter.route('/', revokeRoute)

// ── User connections router (under /api/oauth) ─────────────────────────────────
const oauthConnectionsRouter = new Hono<AppEnv>()
oauthConnectionsRouter.use('*', authMiddleware)
oauthConnectionsRouter.route('/', connectionsRoute)

// ── Admin clients router (under /api/admin/oauth) ─────────────────────────────
const oauthAdminRouter = new Hono<AppEnv>()
oauthAdminRouter.use('*', adminAuthMiddleware)
oauthAdminRouter.use('*', requireAdminSession())
oauthAdminRouter.route('/clients', adminOAuthClientsRoute)

export { oauthRouter, oauthConnectionsRouter, oauthAdminRouter }
