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

const router = express.Router();

router.get('/', auth, (req, res) => {
  const { page = 1, limit = 20, type, riskLevel, search } = req.query;
  const offset = (page - 1) * limit;
  
  let query = 'SELECT i.*, u.full_name as created_by_name FROM investors i LEFT JOIN users u ON i.created_by = u.id WHERE 1=1';
  const params = [];
  
  if (type) {
    query += ' AND i.type = ?';
    params.push(type);
  }
  
  if (riskLevel) {
    query += ' AND i.risk_level = ?';
    params.push(riskLevel);
  }
  
  if (search) {
    query += ' AND (i.name LIKE ? OR i.company LIKE ? OR i.email LIKE ?)';
    const searchTerm = `%${search}%`;
    params.push(searchTerm, searchTerm, searchTerm);
  }
  
  query += ' ORDER BY i.created_at DESC LIMIT ? OFFSET ?';
  params.push(parseInt(limit), offset);
  
  const investors = db.prepare(query).all(...params);
  
  let countQuery = query.replace(/SELECT.*FROM/, 'SELECT COUNT(*) as total FROM').replace(/ORDER BY.*$/, '').replace(/ LIMIT \? OFFSET \?$/, '');
  const countParams = params.slice(0, -2);
  const countResult = db.prepare(countQuery).get(...countParams);
  
  res.json({
    investors,
    pagination: {
      page: parseInt(page),
      limit: parseInt(limit),
      total: countResult?.total || 0
    }
  });
});

router.get('/:id', auth, (req, res) => {
  const investorId = parseInt(req.params.id);
  
  const investor = db.prepare('SELECT i.*, u.full_name as created_by_name FROM investors i LEFT JOIN users u ON i.created_by = u.id WHERE i.id = ?').get(investorId);
  if (!investor) {
    return res.status(404).json({ message: '投资者不存在' });
  }
  
  const investments = db.prepare('SELECT pi.*, p.name as project_name, p.code as project_code FROM project_investors pi JOIN projects p ON pi.project_id = p.id WHERE pi.investor_id = ? ORDER BY pi.investment_date DESC').all(investorId);
  
  res.json({ investor, investments: investments || [] });
});

router.post('/', auth, [
  body('name').notEmpty().withMessage('投资者名称不能为空')
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  const { name, type, company, email, phone, address, contactPerson, totalInvestment, riskLevel, tags, notes } = req.body;

  const result = db.prepare(
    'INSERT INTO investors (name, type, company, email, phone, address, contact_person, total_investment, risk_level, tags, notes, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
  ).run(name, type || 'individual', company || '', email || '', phone || '', address || '', contactPerson || '', totalInvestment || 0, riskLevel || 'medium', tags ? JSON.stringify(tags) : null, notes || '', req.user.id);

  res.status(201).json({ message: '投资者创建成功', investorId: result.lastInsertRowid });
});

router.put('/:id', auth, [
  body('name').optional().notEmpty().withMessage('投资者名称不能为空')
], (req, res) => {
  const investorId = parseInt(req.params.id);
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  const { name, type, company, email, phone, address, contactPerson, totalInvestment, riskLevel, tags, notes } = req.body;

  const investor = db.prepare('SELECT * FROM investors WHERE id = ?').get(investorId);
  if (!investor) {
    return res.status(404).json({ message: '投资者不存在' });
  }

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

  if (name !== undefined) updates.push('name = ?'), params.push(name);
  if (type !== undefined) updates.push('type = ?'), params.push(type);
  if (company !== undefined) updates.push('company = ?'), params.push(company);
  if (email !== undefined) updates.push('email = ?'), params.push(email);
  if (phone !== undefined) updates.push('phone = ?'), params.push(phone);
  if (address !== undefined) updates.push('address = ?'), params.push(address);
  if (contactPerson !== undefined) updates.push('contact_person = ?'), params.push(contactPerson);
  if (totalInvestment !== undefined) updates.push('total_investment = ?'), params.push(totalInvestment);
  if (riskLevel !== undefined) updates.push('risk_level = ?'), params.push(riskLevel);
  if (tags !== undefined) updates.push('tags = ?'), params.push(JSON.stringify(tags));
  if (notes !== undefined) updates.push('notes = ?'), params.push(notes);

  if (updates.length === 0) {
    return res.status(400).json({ message: '没有提供更新数据' });
  }

  updates.push('updated_at = CURRENT_TIMESTAMP');
  params.push(investorId);

  db.prepare(`UPDATE investors SET ${updates.join(', ')} WHERE id = ?`).run(...params);
  res.json({ message: '投资者更新成功' });
});

router.delete('/:id', auth, authorize('admin', 'investment_manager'), (req, res) => {
  const investorId = parseInt(req.params.id);
  
  const investor = db.prepare('SELECT * FROM investors WHERE id = ?').get(investorId);
  if (!investor) {
    return res.status(404).json({ message: '投资者不存在' });
  }

  const count = db.prepare('SELECT COUNT(*) as count FROM project_investors WHERE investor_id = ?').get(investorId);
  if (count && count.count > 0) {
    return res.status(400).json({ message: '该投资者有关联的投资记录，无法删除' });
  }

  db.prepare('DELETE FROM investors WHERE id = ?').run(investorId);
  res.json({ message: '投资者删除成功' });
});

module.exports = router;
