require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs');

const dataDir = path.join(__dirname, '../data');
if (!fs.existsSync(dataDir)) {
  fs.mkdirSync(dataDir);
}

const app = express();
const PORT = process.env.PORT || 3001;

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use('/api/auth', require('./routes/auth'));
app.use('/api/users', require('./routes/users'));
app.use('/api/projects', require('./routes/projects'));
app.use('/api/investors', require('./routes/investors'));
app.use('/api/news', require('./routes/news'));
app.use('/api/notifications', require('./routes/notifications'));
app.use('/api/activity', require('./routes/activity'));
app.use('/api/candidate-projects', require('./routes/candidate_projects'));
app.use('/api/knowledge', require('./routes/knowledge'));
app.use('/api/learning-progress', require('./routes/learning_progress'));
app.use('/api/project-permissions', require('./routes/project_permissions'));
app.use('/api/decision-process', require('./routes/decision_process'));
app.use('/api/post-investment', require('./routes/post_investment'));
app.use('/api/institutions', require('./routes/institutions'));
app.use('/api/incubation-projects', require('./routes/incubation_projects'));

app.get('/api/health', (req, res) => {
  res.json({ message: 'PE投资管理系统API运行正常', timestamp: new Date().toISOString() });
});

app.use(express.static(path.join(__dirname, '../client/build')));

app.get('*', (req, res) => {
  const indexPath = path.join(__dirname, '../client/build/index.html');
  if (fs.existsSync(indexPath)) {
    res.sendFile(indexPath);
  } else {
    res.json({ message: '请先构建前端应用' });
  }
});

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: '服务器内部错误' });
});

app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
  console.log(`默认管理员账户: admin / admin123`);
});
