// Cloudflare Worker example for Google Calendar integration

// Your Google Calendar API base URL
const GOOGLE_CALENDAR_API_BASE_URL = 'https://www.googleapis.com/calendar/v3';

// Replace 'YOUR_GOOGLE_CALENDAR_API_KEY' with your actual Google Calendar API key
const GOOGLE_CALENDAR_API_KEY = 'YOUR_GOOGLE_CALENDAR_API_KEY';

// Replace 'YOUR_CALENDAR_ID' with your actual public holiday calendar ID
const CALENDAR_ID = 'YOUR_CALENDAR_ID';

// Replace 'YOUR_TELEGRAM_BOT_TOKEN' with your actual Telegram bot token
const TELEGRAM_BOT_TOKEN = '6489390855:AAHRAjPEKnT8DaVG50KYnR-lbKDadpbJiAA';

// Cloudflare Worker code
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

/**
 * Sends a Telegram response to the specified chat ID with the given message.
 * @param {string} chatId - The chat ID where the message will be sent.
 * @param {string} message - The message to send.
 * @returns {Response} - The response from the Telegram API.
 */
async function sendTelegramResponse(chatId, message) {
  const apiUrl = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`;
  const params = {
    chat_id: chatId,
    text: message,
  };

  try {
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params),
    });

    if (response.ok) {
      return new Response('Message sent successfully!', { status: 200 });
    } else {
      return new Response('Failed to send message.', { status: 500 });
    }
  } catch (error) {
    console.error(error);
    return new Response('Error occurred while sending the message.', { status: 500 });
  }
}

/**
 * Retrieves upcoming holidays from Google Calendar API.
 * @returns {Array} - An array of upcoming holidays with name and date.
 */
async function getUpcomingHolidays() {
  const url = `${GOOGLE_CALENDAR_API_BASE_URL}/calendars/${encodeURIComponent(CALENDAR_ID)}/events?key=${GOOGLE_CALENDAR_API_KEY}&timeMin=${encodeURIComponent(new Date().toISOString())}&maxResults=5&orderBy=startTime&singleEvents=true`;

  try {
    const response = await fetch(url);

    const data = await response.json();
    const events = data.items;
    if (!events || events.length === 0) {
      return [];
    }

    return events.map(event => {
      return {
        name: event.summary,
        date: event.start.date || event.start.dateTime,
      };
    });
  } catch (error) {
    console.error('Error fetching holidays:', error);
    return [];
  }
}

/**
 * Handles incoming requests and responds with the appropriate action.
 * @param {Request} request - The incoming request to handle.
 * @returns {Response} - The response to the request.
 */
async function handleRequest(request) {
  const { method, headers } = request;

  const url = new URL(request.url);

  // Check if the request is a POST request to /webhooks/telegram and has JSON content-type
  if (method === 'POST' && url.pathname == '/webhooks/telegram' && headers.get('content-type') === 'application/json') {
    const data = await request.json();
    const { message } = data;

    if (1 == 1) {
      // const command = message.text.trim();

      // if (command.startsWith('/holidays')) {
      // if (command) {
        // const holidays = await getUpcomingHolidays();
        // const response = formatHolidaysResponse('123');

        const response = 'prd 最近5分钟,error日志条数大于1'

        // const chatId = message.chat.id
        const chatId = "-1001959173605"

        await sendTelegramResponse(chatId, response)

        return new Response('OK', { status: 200 });
      // }
    }
  }

  return new Response('OK', { status: 200 });
}

/**
 * Formats the list of upcoming holidays into a readable response for Telegram.
 * @param {Array} holidays - The array of upcoming holidays.
 * @returns {string} - The formatted response for Telegram.
 */
function formatHolidaysResponse(holidays) {
  if (holidays.length === 0) {
    return 'No upcoming holidays found.';
  }

  const formattedHolidays = holidays.map(holiday => `- ${holiday.name} - ${holiday.date}`).join('\n');
  return `Upcoming holidays in your country:\n${formattedHolidays}`;
}