import { createStore } from "./createStore";
import type { TokenResponse, UserInfo } from "@/types/auth.types";
import { persistRefreshToken } from "@/lib/initAuth";

interface AuthState {
  accessToken: string | null;
  refreshToken: string | null;
  user: UserInfo | null;
  authReady: boolean;
}

const storedRefresh = typeof localStorage !== "undefined" ? localStorage.getItem("dm_refresh_token") : null;

const initialState: AuthState = {
  accessToken: null,
  refreshToken: storedRefresh,
  user: null,
  authReady: !storedRefresh,
};

export const authStore = createStore<AuthState>(initialState);

export function setTokens(tokens: TokenResponse): void {
  authStore.setState({
    accessToken: tokens.accessToken,
    refreshToken: tokens.refreshToken,
  });
  persistRefreshToken(tokens.refreshToken);
}

export function setUser(user: UserInfo | null): void {
  authStore.setState({ user });
}

export function setAuthReady(ready: boolean): void {
  authStore.setState({ authReady: ready });
}

export function clearAuth(): void {
  persistRefreshToken(null);
  authStore.setState({ accessToken: null, refreshToken: null, user: null, authReady: true });
}

export const getAccessToken = (): string | null => authStore.getState().accessToken;
export const getRefreshToken = (): string | null => authStore.getState().refreshToken;
export const isAuthenticated = (): boolean => Boolean(authStore.getState().accessToken);
export const isAuthReady = (): boolean => authStore.getState().authReady;
