import { Hono } from 'hono' import type { Env } from '../index' import { requireAuth } from '../middlewares/auth' export const messagesRoutes = new Hono<{ Bindings: Env }>() messagesRoutes.get('/', requireAuth, async (c) => { const page = Math.max(1, Number(c.req.query('page') || 1)) const limit = Math.min(100, Math.max(1, Number(c.req.query('limit') || 20))) const q = (c.req.query('q') || '').trim() const from = (c.req.query('from') || '').trim() const startTs = Number(c.req.query('start_ts') || 0) const endTs = Number(c.req.query('end_ts') || 0) const offset = (page - 1) * limit const whereParts: string[] = [] const params: any[] = [] if (from) { whereParts.push('from_number = ?') params.push(from) } if (q) { whereParts.push('(from_number LIKE ? OR content LIKE ?)') params.push(`%${q}%`, `%${q}%`) } if (startTs > 0) { whereParts.push('timestamp >= ?') params.push(startTs) } if (endTs > 0) { whereParts.push('timestamp <= ?') params.push(endTs) } const where = whereParts.length ? `WHERE ${whereParts.join(' AND ')}` : '' const totalStmt = c.env.DB.prepare(`SELECT COUNT(*) as cnt FROM sms_messages ${where}`) const total = (await totalStmt.bind(...params).first() as any)?.cnt || 0 const stmt = c.env.DB.prepare( `SELECT * FROM sms_messages ${where} ORDER BY timestamp DESC LIMIT ? OFFSET ?` ) const rows = await stmt.bind(...params, limit, offset).all() const fromRows = await c.env.DB.prepare( `SELECT DISTINCT from_number FROM sms_messages ORDER BY from_number` ).all() return c.json({ success: true, data: rows.results || [], total, page, limit, from_numbers: (fromRows.results || []).map((r: any) => r.from_number), }) }) messagesRoutes.get('/:id', requireAuth, async (c) => { const id = c.req.param('id') const stmt = c.env.DB.prepare(`SELECT * FROM sms_messages WHERE id = ?`) const row = await stmt.bind(id).first() if (!row) return c.json({ success: false, error: '消息不存在' }, 404) return c.json({ success: true, data: row }) })