import { assetManager } from 'cc';

const RESOURCES_BUNDLE = 'resources';

let bundlePromise: Promise<assetManager.Bundle> | null = null;

/** 拆分分包后须先 loadBundle('resources')，resources.load 才可用 */
export function ensureResourcesBundle(): Promise<assetManager.Bundle> {
    const existing = assetManager.getBundle(RESOURCES_BUNDLE);
    if (existing) return Promise.resolve(existing);
    if (bundlePromise) return bundlePromise;
    bundlePromise = new Promise((resolve, reject) => {
        assetManager.loadBundle(RESOURCES_BUNDLE, (err, bundle) => {
            bundlePromise = null;
            if (err || !bundle) {
                reject(err ?? new Error(`bundle "${RESOURCES_BUNDLE}" unavailable`));
                return;
            }
            resolve(bundle);
        });
    });
    return bundlePromise;
}
