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

const app = express();
const PORT = process.env.PORT || 3001;
const DATA_FILE = path.join(__dirname, 'user-data.json');

// 中间件
app.use(cors());
app.use(express.json({ limit: '10mb' }));

// 静态文件服务
app.use(express.static(path.join(__dirname, 'dist')));

// 确保数据文件存在
async function ensureDataFile() {
  try {
    await fs.access(DATA_FILE);
  } catch {
    // 文件不存在，创建空的数据结构
    await fs.writeFile(DATA_FILE, JSON.stringify({
      tasks: [],
      projects: [],
      lastUpdated: new Date().toISOString()
    }));
  }
}

// API路由
app.get('/api/data', async (req, res) => {
  try {
    await ensureDataFile();
    const data = await fs.readFile(DATA_FILE, 'utf8');
    const userData = JSON.parse(data);
    res.json(userData);
  } catch (error) {
    console.error('获取数据失败:', error);
    res.status(500).json({ error: '获取数据失败' });
  }
});

app.post('/api/data', async (req, res) => {
  try {
    const { tasks, projects } = req.body;
    
    // 验证数据格式
    if (!Array.isArray(tasks) || !Array.isArray(projects)) {
      return res.status(400).json({ error: '数据格式不正确' });
    }
    
    const userData = {
      tasks,
      projects,
      lastUpdated: new Date().toISOString()
    };
    
    await fs.writeFile(DATA_FILE, JSON.stringify(userData, null, 2));
    
    res.json({ 
      success: true, 
      message: '数据保存成功',
      lastUpdated: userData.lastUpdated
    });
  } catch (error) {
    console.error('保存数据失败:', error);
    res.status(500).json({ error: '保存数据失败' });
  }
});

app.get('/api/last-updated', async (req, res) => {
  try {
    await ensureDataFile();
    const data = await fs.readFile(DATA_FILE, 'utf8');
    const userData = JSON.parse(data);
    res.json({ lastUpdated: userData.lastUpdated });
  } catch (error) {
    console.error('获取更新时间失败:', error);
    res.status(500).json({ error: '获取更新时间失败' });
  }
});

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// 处理所有前端路由，返回index.html
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 服务器运行在 http://localhost:${PORT}`);
  console.log(`📱 前端应用: http://localhost:${PORT}`);
  console.log(`🔧 API端点:`);
  console.log(`  GET  /api/data - 获取用户数据`);
  console.log(`  POST /api/data - 保存用户数据`);
  console.log(`  GET  /api/last-updated - 获取最后更新时间`);
  console.log(`  GET  /api/health - 健康检查`);
  console.log(`📊 健康检查: http://localhost:${PORT}/api/health`);
});

module.exports = app; 