import axios from 'axios';

const API_SPEED_URL = import.meta.env.VITE_API_SPEED_URL;
const API_PING_URL = import.meta.env.VITE_API_PING_URL;
const API_METRICS_URL = import.meta.env.VITE_API_METRICS_URL;

// console.log(import.meta.env.VITE_API_URL)

export const fetchSpeedTestData = async () => {
  try {
    const response = await axios.get(API_SPEED_URL, {
      headers: {
        'Author': 'vedeom',
      },
    });

    console.log('API Response:', response.data); // Log seluruh response
    console.log('Parsed Data:', response.data.data || []); // Log data yang diproses

    return response.data.data || [];
  } catch (error) {
    console.error('API Fetch Error:', error.message); // Log error jika terjadi kesalahan
    throw new Error(error.message);
  }
};

export const fetchActiveDevices = async () => {
  try {
    const response = await axios.get(API_PING_URL);

    // console.log('Devices API Response:', response.data);

    // Pastikan response.data adalah array
    const dataArray = Array.isArray(response.data) ? response.data : [];

    // Konversi data API ke format yang sesuai
    const formattedDevices = dataArray.flatMap(item =>
      item.result.map(device => ({
        id: item.id,  // Menggunakan id dari API sebagai key
        ip: device.target,  // IP Address
        name: device.devices, // Nama perangkat
        is_online: device.alive === 1 ? "Online" : "Offline" // Status perangkat
      }))
    );

    // console.log('Parsed Devices:', formattedDevices);
    return formattedDevices;
  } catch (error) {
    console.error('Devices API Fetch Error:', error.message);
    return [];
  }
};

export const fetchMetricsData = async () => {
  try {
    console.log("Fetching Metrics from:", API_METRICS_URL);

    const response = await axios.get(API_METRICS_URL);
    console.log("Raw API Response:", response.data);

    // Validasi bahwa `response.data` adalah array dan memiliki elemen pertama
    if (!response.data || !Array.isArray(response.data) || response.data.length === 0) {
      console.error("Invalid API response structure:", response.data);
      return [];
    }

    const metricsData = response.data[0]; // Ambil object pertama dari array

    // Pastikan objek memiliki properti yang dibutuhkan
    if (!metricsData.monitor_response_time || !metricsData.monitor_response_time.metrics) {
      console.error("Missing 'monitor_response_time' in response:", metricsData);
      return [];
    }
    if (!metricsData.monitor_status || !metricsData.monitor_status.metrics) {
      console.error("Missing 'monitor_status' in response:", metricsData);
      return [];
    }
    if (!metricsData.monitor_cert_is_valid || !metricsData.monitor_cert_is_valid.metrics) {
      console.error("Missing 'monitor_cert_is_valid' in response:", metricsData);
      return [];
    }
    if (!metricsData.monitor_cert_days_remaining || !metricsData.monitor_cert_days_remaining.metrics) {
      console.error("Missing 'monitor_cert_days_remaining' in response:", metricsData);
      return [];
    }

    const responseTimes = metricsData.monitor_response_time.metrics;
    const statuses = metricsData.monitor_status.metrics;
    const certValidations = metricsData.monitor_cert_is_valid.metrics;
    const certDaysRemaining = metricsData.monitor_cert_days_remaining.metrics;

    // Gabungkan semua data berdasarkan monitor_url
    const metrics = responseTimes.map(rt => {
      const status = statuses.find(s => s.labels.monitor_url === rt.labels.monitor_url);
      const certValid = certValidations.find(c => c.labels.monitor_url === rt.labels.monitor_url);
      const certDays = certDaysRemaining.find(d => d.labels.monitor_url === rt.labels.monitor_url);

      return {
        monitor_name: rt.labels.monitor_name,
        monitor_url: rt.labels.monitor_url,
        response_time: rt.value,
        status: status ? status.value : 0, // Default 0 jika tidak ditemukan
        cert_valid: certValid ? certValid.value : 0, // Default 0 jika tidak ditemukan
        cert_days_remaining: certDays ? certDays.value : "N/A" // Default "N/A" jika tidak ditemukan
      };
    });

    console.log("Final Metrics Data:", metrics);
    return metrics;
  } catch (error) {
    console.error("Error fetching metrics:", error);
    return [];
  }
};



