/**
 * Portal KB routes — tenant-portals (wave 9d, Task 9).
 *
 * GET /api/portal/kb/spaces
 * GET /api/portal/kb/articles/:id
 * GET /api/portal/kb/attachments/:id/url
 */
import { Hono } from 'hono'
import { kbPortalQuery } from '@zync/db/queries'
import type { AppEnv } from '../../types'
import { portalAuthMiddleware, type PortalAuthVariables } from '../../middleware/portalAuth'
import { signKbUrl } from '../../lib/kb-storage'

type PortalDataEnv = {
  Bindings: AppEnv['Bindings']
  Variables: PortalAuthVariables
}

export const portalKbRoutes = new Hono<PortalDataEnv>()

portalKbRoutes.use('*', portalAuthMiddleware)

portalKbRoutes.get('/spaces', async (c) => {
  const portal = c.get('portal')
  const db = c.get('db')
  const spaces = await kbPortalQuery(db, portal.tenantId, portal.customerId).listAccessibleSpaces()
  return c.json({ spaces }, 200)
})

portalKbRoutes.get('/spaces/:id/articles', async (c) => {
  const portal = c.get('portal')
  const db = c.get('db')
  const tree = await kbPortalQuery(db, portal.tenantId, portal.customerId).listPublishedArticleTree(
    c.req.param('id'),
  )
  return c.json({ items: tree }, 200)
})

portalKbRoutes.get('/articles/:id', async (c) => {
  const portal = c.get('portal')
  const db = c.get('db')
  const article = await kbPortalQuery(db, portal.tenantId, portal.customerId).getPublishedArticleById(
    c.req.param('id'),
  )
  if (!article) return c.json({ error: 'Not found' }, 404)
  return c.json({ article }, 200)
})

portalKbRoutes.get('/articles/:id/attachments', async (c) => {
  const portal = c.get('portal')
  const db = c.get('db')
  const attachments = await kbPortalQuery(db, portal.tenantId, portal.customerId).listAttachments(
    c.req.param('id'),
  )
  return c.json({ attachments }, 200)
})

portalKbRoutes.get('/attachments/:id/url', async (c) => {
  const portal = c.get('portal')
  const db = c.get('db')
  const attachment = await kbPortalQuery(db, portal.tenantId, portal.customerId).getAttachment(
    c.req.param('id'),
  )
  if (!attachment) return c.json({ error: 'Not found' }, 404)

  const ttlSeconds = 3600
  const url = await signKbUrl(c.env, attachment.r2Key, ttlSeconds)
  const expiresAt = new Date(Date.now() + ttlSeconds * 1000).toISOString()

  return c.json({ url, expiresAt }, 200)
})
