const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const googleTrends = require('google-trends-api');

const app = express();
const PORT = 3000;

// Bật CORS cho tất cả các nguồn gốc
app.use(cors());

// Middleware để parse JSON
app.use(bodyParser.json());

// API lấy dữ liệu từ Google Trends trong vòng 30 ngày tại khu vực US
app.post('/api/get-trends', async (req, res) => {
  const { keywords } = req.body;

  if (!keywords || !Array.isArray(keywords)) {
    return res.status(400).json({ error: 'Danh sách từ khóa không hợp lệ' });
  }

  try {
    const trendsData = {};
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(endDate.getDate() - 30);  // Tính ngày 30 ngày trước

    // Sử dụng Promise.all để gửi nhiều từ khóa cùng lúc
    const results = await googleTrends.interestOverTime({
      keyword: keywords,          // Truyền vào mảng các từ khóa
      startTime: startDate,       // Thời gian bắt đầu là 30 ngày trước
      endTime: endDate,           // Thời gian kết thúc là hiện tại
      geo: 'US'                   // Khu vực là Hoa Kỳ (US)
    });

    // Chuyển kết quả trả về thành đối tượng
    const parsedResults = JSON.parse(results).default.timelineData;

    // Lưu kết quả theo từ khóa
    keywords.forEach((keyword, index) => {
      trendsData[keyword] = parsedResults.map(item => ({
        time: item.formattedTime,
        value: item.value[index],  // Giá trị của từng từ khóa
      }));
    });

    // Trả lại dữ liệu cho frontend
    res.json(trendsData);
  } catch (error) {
    console.error('Lỗi khi lấy dữ liệu Google Trends:', error);
    res.status(500).json({ error: 'Không thể lấy dữ liệu Google Trends' });
  }
});

// Khởi động server
app.listen(PORT, () => {
  console.log(`Server đang chạy tại http://localhost:${PORT}`);
});
