import { Hono } from 'hono'
import { DB } from '../db.js'

const app = new Hono()

/**
 * GET /api/audit?action=&actor_phone=&page=&size=
 * 操作日志查询（运营 Tab）
 */
app.get('/', async (c) => {
  const action = c.req.query('action') || ''
  const phone  = c.req.query('actor_phone') || ''
  const page   = Math.max(1, parseInt(c.req.query('page') || '1'))
  const size   = Math.min(200, Math.max(1, parseInt(c.req.query('size') || '50')))

  const where = ['1=1']
  const args = []
  if (action) { where.push('action = ?'); args.push(action) }
  if (phone)  { where.push('actor_phone = ?'); args.push(phone) }

  const total = await DB.prepare(
    `SELECT COUNT(*) AS n FROM audit_logs WHERE ${where.join(' AND ')}`
  ).bind(...args).first()

  const { results } = await DB.prepare(
    `SELECT id, ts, action, actor_name, actor_phone, actor_email,
            target_type, target_id, target_name, ip, ua, meta
     FROM audit_logs
     WHERE ${where.join(' AND ')}
     ORDER BY ts DESC
     LIMIT ? OFFSET ?`
  ).bind(...args, size, (page - 1) * size).all()

  return c.json({ data: results || [], total: total?.n || 0, page, size })
})

export default app
