const express = require('express');
const db = require('../db');
const { authenticate, requireAdmin } = require('../middleware/auth');

const router = express.Router();

router.get('/', async (req, res) => {
  try {
    const result = await db.query(`
      SELECT pr.*, pn.name as node_name, p.name as project_name
      FROM payment_records pr
      LEFT JOIN payment_nodes pn ON pr.node_id = pn.id
      LEFT JOIN projects p ON pn.project_id = p.id
      ORDER BY pr.payment_date DESC
      LIMIT 50
    `);
    res.json({ success: true, data: result.rows, count: result.rows.length });
  } catch (error) {
    console.error('获取付款记录失败:', error);
    res.status(500).json({ success: false, message: '获取付款记录失败' });
  }
});

router.post('/', authenticate, async (req, res) => {
  try {
    const { node_id, amount, payment_date, method, status } = req.body;
    const result = await db.query(
      'INSERT INTO payment_records (node_id, amount, payment_date, method, status) VALUES ($1, $2, $3, $4, $5)',
      [node_id, amount || 0, payment_date, method, status || 'completed']
    );
    res.json({ success: true, data: { id: (result.rows[0]?.id || result.rows?.[0]?.id) }, message: '付款记录创建成功' });
  } catch (error) {
    res.status(500).json({ success: false, message: '创建付款记录失败' });
  }
});

module.exports = router;