import { create } from "zustand";
import { persist } from "zustand/middleware";
import type { AuthUser, TokenResponse } from "@/services/authService";

interface AuthStore {
  token: string | null;
  user: AuthUser | null;
  expiresAt: string | null;
  hydrated: boolean;
  setHydrated: (value: boolean) => void;
  setSession: (session: TokenResponse) => void;
  logout: () => void;
}

export const useAuthStore = create<AuthStore>()(
  persist(
    (set) => ({
      token: null,
      user: null,
      expiresAt: null,
      hydrated: false,
      setHydrated: (value) => set({ hydrated: value }),
      setSession: (session) => {
        if (typeof window !== "undefined") {
          localStorage.setItem("auth_token", session.access_token);
        }
        set({
          token: session.access_token,
          user: session.user,
          expiresAt: session.expires_at,
        });
      },
      logout: () => {
        if (typeof window !== "undefined") {
          localStorage.removeItem("auth_token");
        }
        set({ token: null, user: null, expiresAt: null });
      },
    }),
    {
      name: "user",
      partialize: (state) => ({
        token: state.token,
        user: state.user,
        expiresAt: state.expiresAt,
      }),
      onRehydrateStorage: () => (state) => {
        state?.setHydrated(true);
      },
    }
  )
);
