import { defineStore } from "pinia";
import { useNuxtApp } from "#app";

export const useServiceStore = defineStore("service", () => {
  const { $axios } = useNuxtApp();

  const errors = ref({});
  const isLoading = ref(false);
  const services = ref([]);
  const service = ref(null);
  async function getServices() {
    isLoading.value = true;
    const result = await $axios.get(`services`);
    if (result.status >= 200) {
      services.value = result.data.data;
      isLoading.value = false;
    }
  }
  async function getServiceById(id) {
    isLoading.value = true;

    try {
      const result = await $axios.get(`/services/${id}`);

      if (result.data?.message === "Service Not Found") {
        service.value = null;
      } else {
        service.value = result.data.data;
      }
    } catch (error) {
      service.value = null;
    } finally {
      isLoading.value = false;
    }
  }

  async function getServiceBySlug(slug) {
    isLoading.value = true;

    try {
      const result = await $axios.get(`/services/show/${slug}`);

      if (result.data?.message === "Service Not Found") {
        service.value = null;
      } else {
        service.value = result.data.data;
      }
    } catch (error) {
      service.value = null;
    } finally {
      isLoading.value = false;
    }
  }
  function slugify(text) {
    return text
      .toString()
      .toLowerCase()
      .trim()
      .replace(/\s+/g, "-") // Replace spaces with -
      .replace(/[؟,،!%&]/g, "") // Remove Arabic punctuation
      .replace(/-+/g, "-"); // Remove multiple -
  }

  return {
    errors,
    isLoading,
    services,
    service,
    getServices,
    getServiceById,
    getServiceBySlug,
    slugify,
  };
});
