const express = require('express');
const db = require('../config/database');
const { authenticate } = require('../middleware/auth');
const { asyncHandler, AppError } = require('../middleware/errorHandler');

const router = express.Router();

// 搜索账目
router.get('/', authenticate, asyncHandler(async (req, res) => {
  const { q } = req.query;

  if (!q) {
    throw new AppError('请输入搜索关键词', 400, 'MISSING_QUERY');
  }

  const stmt = db.prepare(`
    SELECT * FROM records
    WHERE user_id = ? AND (category LIKE ? OR note LIKE ?)
    ORDER BY date DESC, id DESC
    LIMIT 50
  `);

  const records = stmt.all(req.userId, `%${q}%`, `%${q}%`);
  res.json(records);
}));

module.exports = router;
