// stores/permissionStore.ts
import { defineStore } from "pinia";
import { ref } from "vue";
import { useAuthStore } from "./authStore";
import { useStorage } from "@vueuse/core";

export const getUserPermission = defineStore("permissionStore", () => {
  // State
  let permissions = ref<any[]>([]);

  const hasPagePermission = (to_fullPath: string) => {
    // fullPath: "/data-entry/content"
    // fullPath: "/data-entry/content?page=2"
    let index = to_fullPath.indexOf("?");
    if (index != -1) to_fullPath = to_fullPath.substring(0, index);

    let items = to_fullPath.split("/");
    let page_key = items[1] + "_" + items[2];
    // console.log('hasPagePermission page_key ', to_fullPath, page_key);

    return permissions.value.some((p) => p.section_tag === page_key);
  };

  const hasActionPermission = (to_fullPath: string, action_tag: string) => {
    // fullPath: "/data-entry/content?page=2"
    let index = to_fullPath.indexOf("?");
    if (index != -1) to_fullPath = to_fullPath.substring(0, index);

    let items = to_fullPath.split("/");
    let page_key = items[1] + "_" + items[2];
    return permissions.value.some(
      (p) => p.section_tag === page_key && p.action_tag === action_tag
    );
  };

  // const hasPermission = (action: string) => {
  //   return permissions.value.some((p) => p.action_tag === action);
  // };

  // const canAccessPage = (pageTag: string) => {
  //   return permissions.value.some((p) => p.section_tag === pageTag);
  // };

  // Actions
  const fetchUserPermissions = async (projectId?: number) => {
    const { $http: httpService } = useNuxtApp();
    const authStore = useAuthStore();
    if (!authStore.user && !localStorage.getItem("user").length) {
      console.log("No authenticated user found");
      return;
    }
    try {
      const data = {
        project_id: 50,
        project_only: 1,
      };

      const response = await httpService.postRequest(
        // permitApi.permissions.userPermissionTags,
        data
      );

      permissions.value = response.data || [];

      useStorage("permit", permissions.value);

      // console.log(" fetchUserPermissions ", permissions.value);
    } catch (error) {
      console.error("❌ Failed to fetch user permissions:", error);
    }
  };

  const reset = () => {
    permissions.value = [];
  };

  return {
    // State
    permissions,

    // Getters
    hasPagePermission,
    hasActionPermission,

    // Actions
    fetchUserPermissions,
    reset,
  };
});
