import axios from "axios";
import { create } from "zustand";
import { Modules } from "@/types/modules";

interface SettingState {
	userRoles: Modules[];

	fetchUserRoles: () => Promise<void>;
	setUserRoles: (userRoles: Modules[]) => void;
}
interface FetchModulesResponse {
	data: Modules[];
}

export const useGetUserRoles = create<SettingState>()((set) => ({
	userRoles: [],
	setUserRoles: (userRoles) => set({ userRoles }),
	fetchUserRoles: async () => {
		try {
			//const response = await axios.get<{data: Setting[]}>(`${process.env.NEXT_PUBLIC_URL}/api/settings/client`);
			const token = localStorage.getItem("auth_token");
			if (token) {
				const response = await axios.get("/api/auth/getuseraccess", {
					withCredentials: true,
				});
				const data: FetchModulesResponse = response?.data; //await response.json();

				if (response.status === 401) {
					set({ userRoles: [] });
				}
				set({ userRoles: data?.data });
			} else {
				//console.log(data);
				set({ userRoles: [] });
			}
		} catch (error) {
			set({ userRoles: [] });
			console.error("Failed to fetch settings:", error);
		}
	},
}));
