import { create } from "zustand";

interface AuthStore {
  setToken: (token: string, rememberMe?: boolean) => void;
  getToken: () => string | null;
  clearToken: () => void;
  setUserId: (userId: string | number, rememberMe?: boolean) => void;
  getUserId: () => string | null;
  clearUserId: () => void;
}

const useAuthStore = create<AuthStore>(() => ({
  setToken: (token: string, rememberMe: boolean = false) => {
    if (typeof window === "undefined") return;
    if (rememberMe) {
      localStorage.setItem("token", token);
    } else {
      sessionStorage.setItem("token", token);
    }
  },

  getToken: (): string | null => {
    if (typeof window === "undefined") return null;
    const sessionToken = sessionStorage.getItem("token");
    if (sessionToken) {
      return sessionToken;
    }

    const localToken = localStorage.getItem("token");
    if (localToken) {
      return localToken;
    }

    return null;
  },

  clearToken: () => {
    if (typeof window === "undefined") return;
    sessionStorage.removeItem("token");
    localStorage.removeItem("token");
  },

  setUserId: (userId: string | number, rememberMe: boolean = false) => {
    if (typeof window === "undefined") return;
    const userIdString = String(userId);
    if (rememberMe) {
      localStorage.setItem("userId", userIdString);
    } else {
      sessionStorage.setItem("userId", userIdString);
    }
  },

  getUserId: (): string | null => {
    if (typeof window === "undefined") return null;
    const sessionUserId = sessionStorage.getItem("userId");
    if (sessionUserId) {
      return sessionUserId;
    }

    const localUserId = localStorage.getItem("userId");
    if (localUserId) {
      return localUserId;
    }

    return null;
  },

  clearUserId: () => {
    if (typeof window === "undefined") return;
    sessionStorage.removeItem("userId");
    localStorage.removeItem("userId");
  },
}));

export default useAuthStore;
