const express = require('express');
const { body, validationResult } = require('express-validator');
const db = require('../config/database');
const { auth } = require('../middleware/auth');

const router = express.Router();

const DEFAULT_STAGES = [
  '项目立项',
  '初步调研',
  '投资分析',
  '投委会初审',
  '尽职调查',
  '投资条款谈判',
  '投委会终审',
  '投资交割'
];

router.get('/project/:projectId', auth, (req, res) => {
  const projectId = parseInt(req.params.projectId);

  const stages = db.prepare(`
    SELECT dp.*, u.full_name as decided_by_name
    FROM decision_process dp
    LEFT JOIN users u ON dp.decided_by = u.id
    WHERE dp.project_id = ?
    ORDER BY dp.id
  `).all(projectId);

  res.json({ decision_process: stages });
});

router.post('/project/:projectId/init', auth, (req, res) => {
  const projectId = parseInt(req.params.projectId);

  const project = db.prepare('SELECT * FROM projects WHERE id = ?').get(projectId);
  if (!project) {
    return res.status(404).json({ message: '项目不存在' });
  }

  const existing = db.prepare('SELECT * FROM decision_process WHERE project_id = ?').get(projectId);
  if (existing) {
    return res.status(400).json({ message: '决策流程已初始化' });
  }

  const insert = db.prepare('INSERT INTO decision_process (project_id, stage, status) VALUES (?, ?, ?)');
  DEFAULT_STAGES.forEach((stage, index) => {
    const status = index === 0 ? 'in_progress' : 'pending';
    insert.run(projectId, stage, status);
  });

  res.json({ message: '决策流程初始化成功' });
});

router.put('/:stageId', auth, (req, res) => {
  const stageId = parseInt(req.params.stageId);
  const { status, notes } = req.body;

  const stage = db.prepare('SELECT * FROM decision_process WHERE id = ?').get(stageId);
  if (!stage) {
    return res.status(404).json({ message: '阶段不存在' });
  }

  const updates = [];
  const params = [];

  if (status !== undefined) {
    updates.push('status = ?');
    params.push(status);
    if (status === 'completed' || status === 'rejected') {
      updates.push('decided_by = ?, decided_at = CURRENT_TIMESTAMP');
      params.push(req.user.id);
    }
  }
  if (notes !== undefined) {
    updates.push('notes = ?');
    params.push(notes);
  }

  params.push(stageId);
  db.prepare(`UPDATE decision_process SET ${updates.join(', ')} WHERE id = ?`).run(...params);

  if (status === 'completed') {
    const allStages = db.prepare('SELECT * FROM decision_process WHERE project_id = ? ORDER BY id').all(stage.project_id);
    const currentIndex = allStages.findIndex(s => s.id === stageId);

    if (currentIndex < allStages.length - 1) {
      const nextStage = allStages[currentIndex + 1];
      db.prepare('UPDATE decision_process SET status = ? WHERE id = ?').run('in_progress', nextStage.id);
    } else {
      db.prepare('UPDATE projects SET status = ? WHERE id = ?').run('active', stage.project_id);
    }
  }

  res.json({ message: '阶段更新成功' });
});

router.delete('/:stageId', auth, (req, res) => {
  const stageId = parseInt(req.params.stageId);
  db.prepare('DELETE FROM decision_process WHERE id = ?').run(stageId);
  res.json({ message: '阶段删除成功' });
});

module.exports = router;
