/**
 * GET  /api/oauth/connections       — list user's OAuth app connections (wave-12)
 * DELETE /api/oauth/connections/:clientId — disconnect an OAuth app
 *
 * Both routes are authenticated (authMiddleware applied in oauth/index.ts).
 */
import { Hono } from 'hono'
import {
  createDb,
  getOAuthClientByClientId,
  listOAuthConnectionsForUser,
  revokeClientConnectionTokens,
} from '@zync/db/queries'
import type { AppEnv } from '../../types'
import type { SessionPayload } from '@zync/types'

const connectionsRoute = new Hono<AppEnv>()

connectionsRoute.get('/connections', async (c) => {
  const session = c.get('session') as SessionPayload
  if (!session.tid) return c.json({ error: 'No active tenant' }, 409)

  const db = createDb(c.env)
  const connections = await listOAuthConnectionsForUser(db, session.tid, session.sub)
  return c.json({ connections })
})

connectionsRoute.delete('/connections/:clientId', async (c) => {
  const session = c.get('session') as SessionPayload
  if (!session.tid) return c.json({ error: 'No active tenant' }, 409)

  const { clientId } = c.req.param()
  const db = createDb(c.env)
  const client = await getOAuthClientByClientId(db, clientId)
  if (!client) return c.json({ error: 'not_found', message: 'OAuth client not found' }, 404)

  await revokeClientConnectionTokens(db, {
    oauthClientId: client.id,
    tenantId: session.tid,
    userId: session.sub,
  })

  // Evict KV cache entries for this user+client (best effort)
  // The KV key prefix for OAuth tokens is oauth_at:<tokenHash> — we can't enumerate
  // all hashes, so the eviction happens lazily at token lookup time (resolveOAuthAccessToken
  // checks revokedAt which is now set).

  return c.json({ ok: true })
})

export { connectionsRoute }
