import { getAdminSettings } from "@/api/admin-settings";

const SETTLEMENT_GROUP = "settlement";
const APPLY_REBATE_TO_PAYOUT_KEY = "settlement.apply_rebate_to_payout";

let cachedApplyRebateToPayout: boolean | null = null;
let inflight: Promise<boolean> | null = null;

export function peekApplyRebateToPayoutSetting(): boolean | null {
  return cachedApplyRebateToPayout;
}

export function setCachedApplyRebateToPayoutSetting(value: boolean): void {
  cachedApplyRebateToPayout = value;
}

export function clearCachedSettlementSettings(): void {
  cachedApplyRebateToPayout = null;
  inflight = null;
}

/** 读取「派彩时再扣回水」开关（模块级缓存，避免配置页重复 GET settings） */
export async function loadApplyRebateToPayoutSetting(): Promise<boolean> {
  if (cachedApplyRebateToPayout !== null) {
    return cachedApplyRebateToPayout;
  }
  if (inflight !== null) {
    return inflight;
  }

  inflight = getAdminSettings(SETTLEMENT_GROUP)
    .then((res) => {
      const hit = res.items.find((item) => item.key === APPLY_REBATE_TO_PAYOUT_KEY);
      const value = Boolean(hit?.value ?? false);
      cachedApplyRebateToPayout = value;
      return value;
    })
    .catch(() => false)
    .finally(() => {
      inflight = null;
    });

  return inflight;
}
