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

interface AdminAuthState {
  user: AuthTokenResponse | null;
  setAuth: (user: AuthTokenResponse) => void;
  clearAuth: () => void;
  isAuthenticated: () => boolean;
}

export const useAdminAuthStore = create<AdminAuthState>()(
  persist(
    (set, get) => ({
      user: null,
      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" }
  )
);
