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 pn.*, p.name as project_name, p.code as project_code
      FROM payment_nodes pn
      LEFT JOIN projects p ON pn.project_id = p.id
      ORDER BY pn.due_date ASC
      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 { project_id, name, amount, due_date, status } = req.body;
    const result = await db.query(
      'INSERT INTO payment_nodes (project_id, name, amount, due_date, status) VALUES ($1, $2, $3, $4, $5)',
      [project_id, name, amount || 0, due_date, status || 'pending']
    );
    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;