import { Router } from 'express';
import { weightRecordManager } from '../storage/database';

const router = Router();

// 获取体重记录列表
router.get('/', async (req, res) => {
  try {
    const { userId } = req.query;
    
    if (!userId || typeof userId !== 'string') {
      return res.status(400).json({
        success: false,
        error: 'userId is required'
      });
    }

    const { startDate, endDate } = req.query;
    
    const records = await weightRecordManager.getWeightRecords({
      userId,
      startDate: startDate ? new Date(startDate as string) : undefined,
      endDate: endDate ? new Date(endDate as string) : undefined,
    });

    res.json({
      success: true,
      data: records
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 创建体重记录
router.post('/', async (req, res) => {
  try {
    const record = await weightRecordManager.createWeightRecord(req.body);
    
    res.json({
      success: true,
      data: record
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 删除体重记录
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const success = await weightRecordManager.deleteWeightRecord(id);
    
    res.json({
      success,
      message: success ? 'Record deleted successfully' : 'Record not found'
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 获取体重统计
router.get('/stats', async (req, res) => {
  try {
    const { userId } = req.query;
    
    if (!userId || typeof userId !== 'string') {
      return res.status(400).json({
        success: false,
        error: 'userId is required'
      });
    }

    const stats = await weightRecordManager.getWeightStats(userId);

    res.json({
      success: true,
      data: stats
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

export default router;
