import axios from "axios";
import { fetchCurrentUser } from "@/api/auth.api";
import { setTokens, setUser, authStore } from "@/store/authStore";
import type { TokenResponse } from "@/types/auth.types";

const REFRESH_KEY = "dm_refresh_token";

export function persistRefreshToken(token: string | null): void {
  if (token) {
    localStorage.setItem(REFRESH_KEY, token);
  } else {
    localStorage.removeItem(REFRESH_KEY);
  }
}

export function loadStoredRefreshToken(): string | null {
  return localStorage.getItem(REFRESH_KEY);
}

export async function restoreSession(): Promise<boolean> {
  const stored = loadStoredRefreshToken();
  if (!stored) return false;

  authStore.setState({ refreshToken: stored });

  try {
    const { data } = await axios.post<TokenResponse>("/api/auth/refresh", {
      refreshToken: stored,
    });
    setTokens(data);
    persistRefreshToken(data.refreshToken);
    const user = await fetchCurrentUser();
    setUser(user);
    return true;
  } catch {
    persistRefreshToken(null);
    authStore.setState({ accessToken: null, refreshToken: null, user: null });
    return false;
  }
}
