import { create } from "zustand";
import { persist } from "zustand/middleware";
import type { AuthTokenResponse } from "@/lib/api/types";

interface AdminAuthState {
  user: AuthTokenResponse | null;
  /** True once Zustand has finished rehydrating from localStorage. */
  _hasHydrated: boolean;
  setAuth: (user: AuthTokenResponse) => void;
  clearAuth: () => void;
  isAuthenticated: () => boolean;
  _setHasHydrated: (v: boolean) => void;
}

export const useAdminAuthStore = create<AdminAuthState>()(
  persist(
    (set, get) => ({
      user: null,
      _hasHydrated: false,
      _setHasHydrated: (v) => set({ _hasHydrated: v }),
      setAuth: (user) => {
        if (typeof window !== "undefined") {
          localStorage.setItem("meezi_admin_access_token", user.accessToken);
          localStorage.setItem("meezi_admin_refresh_token", user.refreshToken);
        }
        set({ user });
      },
      clearAuth: () => {
        if (typeof window !== "undefined") {
          localStorage.removeItem("meezi_admin_access_token");
          localStorage.removeItem("meezi_admin_refresh_token");
        }
        set({ user: null });
      },
      isAuthenticated: () => !!get().user?.accessToken,
    }),
    {
      name: "meezi_admin_auth",
      onRehydrateStorage: () => (state) => {
        state?._setHasHydrated(true);
      },
    }
  )
);
