// The Lucia project.
// Copyright 2023-2026 DSP, inc.  All rights reserved.
// Authors:
//   chiayin.kuo@dsp.im (chiayin), 2023/1/31
//   imacat.yang@dsp.im (imacat), 2023/9/23
//   cindy.chang@dsp.im (Cindy Chang), 2024/5/30
/**
 * @module stores/compare Performance comparison dashboard store
 *   for fetching and managing comparison data between two files.
 */

import { defineStore } from "pinia";
import apiClient from "@/api/client.js";
import apiError from "@/module/apiError.js";

/** Pinia store for the Compare Dashboard page data. */
export const useCompareStore = defineStore("compareStore", {
  state: () => ({
    allCompareDashboardData: null,
  }),
  getters: {
    compareDashboardData: (state) => {
      return state.allCompareDashboardData;
    },
  },
  actions: {
    /**
     * Get Performance
     * @param { array } queryParams
     */
    async getCompare(queryParams) {
      // encodeURIComponent encodes special characters in the string to ensure URL correctness.
      const queryString = JSON.stringify(queryParams);
      const api = `/api/compare?datasets=${encodeURIComponent(queryString)}`;

      try {
        const response = await apiClient.get(api);
        this.allCompareDashboardData = response.data;
      } catch (error) {
        apiError(error, "Failed to load the Compare.");
      }
    },
    /**
     * fetch discover api, get stats.
     * @param {string} type - The file type ('log' or 'filter').
     * @param {number} id log or filter ID
     */
    async getStateData(type, id) {
      let api = "";

      switch (type) {
        case "log":
          api = `/api/logs/${id}/discover`;
          break;
        case "filter":
          api = `/api/filters/${id}/discover`;
          break;
        default:
          return null;
      }
      try {
        const response = await apiClient.get(api);

        return response.data.stats;
      } catch (error) {
        apiError(error, "Failed to load the Compare's States.");
        return null;
      }
    },
    /**
     * Get file's name
     * @param {number} id log or filter ID
     */
    async getFileName(id) {
      id = Number(id);
      try {
        const response = await apiClient.get("/api/files");
        const file = response.data.find((i) => i.id === id);

        if (file) return file.name;
      } catch (error) {
        apiError(error, "Failed to load the Compare's file name.");
      }
      return "";
    },
  },
});
