"use client";

import { useEffect } from "react";

import { getAdminCurrencies } from "@/api/admin-currencies";
import type { AdminCurrencyRow } from "@/types/api/admin-currency";

let cachedAdminCurrencies: AdminCurrencyRow[] = [];
let inflightAdminCurrencyLoad: Promise<void> | null = null;

export function getCachedAdminCurrencies(): AdminCurrencyRow[] {
  return cachedAdminCurrencies;
}

export function useAdminCurrencyCatalog() {
  useEffect(() => {
    if (cachedAdminCurrencies.length > 0 || inflightAdminCurrencyLoad !== null) {
      return;
    }

    inflightAdminCurrencyLoad = getAdminCurrencies()
      .then((data) => {
        cachedAdminCurrencies = data.items;
      })
      .catch(() => {
        // 币种目录失败时回退默认 2 位小数，不阻断后台页面。
      })
      .finally(() => {
        inflightAdminCurrencyLoad = null;
      });
  }, []);
}
