"use client";

import { useEffect } from "react";

import { getPublicCurrencies } from "@/api/currency";
import { getPlayerMe } from "@/api/player";
import { loadCurrencyDisplayFormat } from "@/lib/currency-display-settings";
import { usePlayerSessionStore } from "@/stores/player-session-store";

/**
 * 模块加载时已在 {@link lottery-auth} / store 初始态同步恢复 Bearer；
 * 此处再调 `restoreBearerToken` 兜底，并在有 Token 无 `profile` 时补拉 `GET /player/me`。
 */
export function HydratePlayerAuth(): null {
  const restoreBearerToken = usePlayerSessionStore(
    (state) => state.restoreBearerToken,
  );
  const setProfile = usePlayerSessionStore((state) => state.setProfile);
  const setCurrencies = usePlayerSessionStore((state) => state.setCurrencies);

  useEffect(() => {
    usePlayerSessionStore.getState().reconcileSelectedCurrency();
    void loadCurrencyDisplayFormat();
    const refreshFormat = setInterval(() => {
      void loadCurrencyDisplayFormat(true);
    }, 60_000);

    const token = restoreBearerToken();
    void (async () => {
      try {
        if (usePlayerSessionStore.getState().currencies.length === 0) {
          try {
            const currencies = await getPublicCurrencies();
            setCurrencies(currencies.items);
          } catch {
            // 币种元数据失败时不影响登录态恢复。
          }
        }

        if (!token) return;
        if (usePlayerSessionStore.getState().profile !== null) return;

        const me = await getPlayerMe();
        setProfile(me);
      } catch {
        /* 401 由 lottery-http 拦截跳转 */
      }
    })();

    return () => {
      clearInterval(refreshFormat);
    };
  }, [restoreBearerToken, setCurrencies, setProfile]);

  return null;
}
