import axios from "axios";
import { create } from "zustand";
import { User } from "@/types/users";

export type SessionState = {
	user: User | null;
	token: string | null;
	setSession: (user: User | null, token: string | null) => void;
	clearSession: () => void;
};

export const useSessionStore = create<SessionState>((set) => {
	// Initialize token from localStorage, but user remains in memory only
	const storedToken = localStorage.getItem("auth_token");

	return {
		user: null, // User is NOT stored in localStorage
		token: storedToken || null,

		setSession: async (user: any, token) => {
			if (token) {
				localStorage.setItem("auth_token", token);
				const response = await axios.get("/api/auth/session", {
					withCredentials: true,
				});
				const userRoles = await axios.get("/api/auth/getuseraccess", {
					withCredentials: true,
				});
				const data = response.data; //await response.json();

				const rawUser = data.data.user;
				// user.map((u: any) => ({
				// 	...u,
				// 	roles: userRoles.data.data,
				// }));
				user = { ...rawUser, roles: userRoles.data.data };
			} else {
				localStorage.removeItem("auth_token");
			}

			//console.log("Setting session:", {user, token});
			set({ user, token });
		},

		clearSession: () => {
			localStorage.removeItem("auth_token");
			set({ user: null, token: null });
		},
	};
});

export type SessionType = ReturnType<typeof useSessionStore>;
