/**
 * Chat session management routes — ai-assistant.
 *
 * GET    /api/ai-assistant/chat/sessions       → list current user's sessions
 * GET    /api/ai-assistant/chat/sessions/:id   → session + messages
 * DELETE /api/ai-assistant/chat/sessions/:id   → 204 (cascade deletes messages)
 *
 * Auth required. Business tier + ai_assistant module.
 * Enforces ownership: users cannot read/delete other users' sessions.
 */
import { Hono } from 'hono'
import { createDb, listAiChatSessions, getAiChatSession, getAiChatMessages, deleteAiChatSession } from '@zync/db/queries'
import type { AppEnv } from '../../types'
import type { SessionPayload } from '@zync/types'
import { authMiddleware } from '../../middleware/auth'
import { requireTier } from '../../middleware/guards'
import { requireModuleEnabled } from '../../middleware/require-module-enabled'
import { TenantTier } from '@zync/types'

const sessionsRouter = new Hono<AppEnv>()

sessionsRouter.use('*', authMiddleware)
sessionsRouter.use('*', requireModuleEnabled('ai_assistant'))
sessionsRouter.use('*', requireTier(TenantTier.BUSINESS))

// List sessions for the current user
sessionsRouter.get('/', async (c) => {
  const session = c.get('session') as SessionPayload
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const db = createDb(c.env)
  const sessions = await listAiChatSessions(db, session.tid, session.sub, 50)
  return c.json({ sessions })
})

// Get session + messages
sessionsRouter.get('/:id', async (c) => {
  const session = c.get('session') as SessionPayload
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const id = c.req.param('id')
  const db = createDb(c.env)
  const chatSession = await getAiChatSession(db, session.tid, id)

  // Enforce ownership
  if (!chatSession || chatSession.userId !== session.sub) {
    return c.json({ error: 'Not found' }, 404)
  }

  const messages = await getAiChatMessages(db, session.tid, id)

  return c.json({
    session: chatSession,
    messages: messages.map((m) => ({
      id: m.id,
      role: m.role,
      content: m.content,
      createdAt: m.createdAt,
    })),
  })
})

// Delete session (cascade removes messages via FK ON DELETE CASCADE)
sessionsRouter.delete('/:id', async (c) => {
  const session = c.get('session') as SessionPayload
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const id = c.req.param('id')
  const db = createDb(c.env)
  const chatSession = await getAiChatSession(db, session.tid, id)

  // Enforce ownership
  if (!chatSession || chatSession.userId !== session.sub) {
    return c.json({ error: 'Not found' }, 404)
  }

  await deleteAiChatSession(db, session.tid, id)
  return new Response(null, { status: 204 })
})

export { sessionsRouter }
