import { defineStore, storeToRefs } from "pinia";
import { useUserStore } from "./user";

export const useApiStore = defineStore("api", () => {
  const userStore = useUserStore();

  async function fetchData(path = window.location.pathname) {
    const isHomePage = path === "/";
    path = path === "/" ? "/home" : path;
    path = path.startsWith("/") ? path : "/" + path;
    path = path.endsWith("/") ? path.substring(0, path.length - 1) : path;

    const url = `${window.location.origin}${path}.json`;

    try {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      console.log("Données récupérées du chemin " + path, data);
      return data;
    } catch (error) {
      console.error(
        "Une erreur s'est produite lors de la récupération des données pour l'URL :",
        url,
        error
      );
      throw error;
    }
  }

  async function fetchRoute(path, method, data) {
    const config = {
      method: method,
    };

    if (data) {
      config.body = JSON.stringify(data);
    }

    try {
      const response = await fetch(path, config);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      console.log("La route " + path + " a fonctionné.");
      return data;
    } catch (error) {
      console.error("La route " + path + " n'a pas fonctionné.", error);
      throw error;
    }
  }

  async function addComment(comment) {
    const headers = {
      method: "POST",
      body: JSON.stringify(comment),
    };

    try {
      const response = await fetch("/create-comment.json", headers);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const newFile = await response.json();
      return newFile;
    } catch (error) {
      console.error(
        "Une erreur s'est produite lors de l'ajout du commentaire :",
        error
      );
      throw error;
    }
  }

  async function post(data, route) {
    const headers = {
      method: "POST",
      body: JSON.stringify(data),
    };

    try {
      const response = await fetch(route, headers);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      return data;
    } catch (error) {
      console.error("Une erreur s'est produite :", error);
      throw error;
    }
  }

  async function updateComment(comment) {
    const headers = {
      method: "POST",
      body: JSON.stringify(comment),
    };

    try {
      const response = await fetch("/update-comment.json", headers);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const newFile = await response.json();
      return newFile;
    } catch (error) {
      console.error(
        "Une erreur s'est produite lors de la mise à jour du commentaire :",
        comment,
        error
      );
      throw error;
    }
  }

  async function deleteComment(comment) {
    const headers = {
      method: "POST",
      body: JSON.stringify(comment),
    };

    try {
      const response = await fetch("/delete-comment.json", headers);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const newFile = await response.json();
      return newFile;
    } catch (error) {
      console.error(
        "Une erreur s'est produite lors de la suppression du commentaire :",
        comment,
        error
      );
      throw error;
    }
  }

  async function replyComment(comment) {
    const headers = {
      method: "POST",
      body: JSON.stringify(comment),
    };

    try {
      const response = await fetch("/reply-comment.json", headers);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const newFile = await response.json();
      return newFile;
    } catch (error) {
      console.error(
        "Une erreur s'est produite lors de l'ajout de la réponse' :",
        commentaire,
        error
      );
      throw error;
    }
  }

  async function readNotification(notificationId, projectId) {
    const headers = {
      method: "POST",
      body: JSON.stringify({
        projectId,
        notificationId,
      }),
    };
    try {
      const response = await fetch("/read-notification.json", headers);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      if (data.error) {
        throw new Error(data);
      } else {
        if (!projectId.startsWith("/")) {
          projectId = "/" + projectId;
        }
        userStore.readNotification(notificationId, projectId);
        return data;
      }
    } catch (error) {
      throw error;
    }
  }

  async function validateBrief(briefUri, dialogUri = null) {
    const headers = {
      method: "POST",
      body: JSON.stringify({
        briefUri: briefUri,
        dialogUri,
      }),
    };
    try {
      const response = await fetch("/validate-brief.json", headers);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      if (data.error) {
        throw new Error(data);
      } else {
        return data;
      }
    } catch (error) {
      console.log(error);
    }
  }

  async function readAllNotifications() {
    try {
      const response = await fetch("/read-all-notifications.json");
      if (!response.ok) {
        console.log(response);
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      if (data.error) {
        throw new Error(data);
      } else {
        console.log(data);
        userStore.readAllNotifications();
        console.log("All notifications read.");
        return data;
      }
    } catch (error) {
      throw error;
    }
  }

  return {
    fetchData,
    fetchRoute,
    addComment,
    updateComment,
    deleteComment,
    replyComment,
    readNotification,
    readAllNotifications,
    validateBrief,
    post,
  };
});
