"use client";

import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback } from "react";
import { api, type MeResponse } from "@/lib/api";
import { getValidAccessToken } from "@/lib/auth";

export const ME_QUERY_KEY = ["me"] as const;

/** Shared user/tenant session — cached so sidebar navigations do not refetch /me. */
export function useMe() {
  const qc = useQueryClient();
  const q = useQuery({
    queryKey: ME_QUERY_KEY,
    queryFn: async () => {
      const token = await getValidAccessToken();
      if (!token) {
        throw new Error("توکن احراز هویت یافت نشد. لطفاً دوباره وارد شوید.");
      }
      return api.me.get();
    },
    enabled: typeof window !== "undefined",
    staleTime: 5 * 60_000,
    gcTime: 30 * 60_000,
    refetchOnMount: "always",
    refetchOnWindowFocus: true,
    retry: 1,
  });

  const reload = useCallback(async () => {
    const token = await getValidAccessToken();
    if (!token) {
      qc.setQueryData<MeResponse | null>(ME_QUERY_KEY, null);
      return;
    }
    await q.refetch();
  }, [qc, q]);

  return {
    me: q.data ?? null,
    /** True only on the first network load (cached navigations stay instant). */
    loading: q.isLoading,
    error: q.error instanceof Error ? q.error.message : q.error ? String(q.error) : "",
    reload,
  };
}
