const express = require('express');
const db = require('../db');
const router = express.Router();

router.get('/latest', async (req, res) => {
  try {
    const result = await db.query(`
      SELECT e1.currency_code, e1.to_currency_code, e1.rate, e1.effective_date, e1.created_at
      FROM exchange_rates e1
      JOIN (
        SELECT currency_code, to_currency_code, MAX(effective_date) as max_date
        FROM exchange_rates
        WHERE effective_date <= CURRENT_DATE
        GROUP BY currency_code, to_currency_code
      ) e2 ON e1.currency_code = e2.currency_code AND e1.to_currency_code = e2.to_currency_code AND e1.effective_date = e2.max_date
    `);
    const data = {};
    let latestUpdateTime = null;
    result.rows.forEach(row => {
      const pairKey = `${row.currency_code}_${row.to_currency_code}`;
      data[pairKey] = parseFloat(row.rate);
      if (!latestUpdateTime || new Date(row.created_at) > new Date(latestUpdateTime)) {
        latestUpdateTime = row.created_at;
      }
    });
    if (Object.keys(data).length === 0) {
      data.CNY_LAK = 2900;
      data.CNY_USD = 0.143;
      data.CNY_THB = 4.8;
      data.USD_LAK = 20300;
      data.THB_LAK = 604;
    }
    res.json({
      success: true,
      data: data,
      updated_at: latestUpdateTime || new Date().toISOString(),
      date: new Date().toISOString().split('T')[0]
    });
  } catch (error) {
    console.error('获取汇率失败:', error);
    res.status(500).json({ success: false, message: '获取汇率失败' });
  }
});

router.get('/', async (req, res) => {
  try {
    const result = await db.query(`
      SELECT * FROM exchange_rates ORDER BY effective_date DESC LIMIT 20
    `);
    res.json({ success: true, data: result.rows, count: result.rows.length });
  } catch (error) {
    console.error('获取汇率失败:', error);
    res.status(500).json({ success: false, message: '获取汇率失败' });
  }
});

router.get('/history', async (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 20;
    const result = await db.query(`
      SELECT * FROM exchange_rates ORDER BY created_at DESC LIMIT $1
    `, [limit]);
    const formattedData = result.rows.map(row => ({
      ...row,
      pair_key: `${row.currency_code}_${row.to_currency_code}`,
      from_currency: row.currency_code,
      to_currency: row.to_currency_code
    }));
    res.json({ success: true, data: formattedData });
  } catch (error) {
    console.error('获取历史汇率失败:', error);
    res.status(500).json({ success: false, message: '获取历史汇率失败' });
  }
});

router.post('/', async (req, res) => {
  try {
    const { pair_key, rate, effective_date, from_currency, to_currency } = req.body;
    let currencyCode = from_currency;
    let toCurrencyCode = to_currency;
    if (!currencyCode && pair_key) {
      const parts = pair_key.split('_');
      currencyCode = parts[0];
      toCurrencyCode = parts[1];
    }
    if (!currencyCode || !toCurrencyCode || rate === undefined || !effective_date) {
      return res.status(400).json({ success: false, message: '缺少必要参数' });
    }
    const result = await db.query(
      `INSERT INTO exchange_rates (currency_code, to_currency_code, rate, effective_date, created_at)
       VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP) RETURNING *`,
      [currencyCode, toCurrencyCode, rate, effective_date]
    );
    res.json({ success: true, message: '汇率保存成功', data: result.rows[0] });
  } catch (error) {
    console.error('保存汇率失败:', error);
    res.status(500).json({ success: false, message: '保存汇率失败' });
  }
});

module.exports = router;
