import { resources, JsonAsset } from 'cc';
import { IJsonLoader } from '../data/ConfigMgr';

/**
 * Cocos Creator backed JSON loader. Used by Scene Entry components to feed
 * `ConfigMgr`. Production-only: unit tests inject `MapJsonLoader` instead.
 *
 * The path parameter matches what `ConfigMgr` requests, e.g. `configs/enemies`.
 * Cocos resolves it against the `assets/resources/` root.
 */
export class CCJsonLoader implements IJsonLoader {
    public load<T>(path: string): Promise<T> {
        return new Promise<T>((resolve, reject) => {
            resources.load(path, JsonAsset, (err: Error | null, asset: unknown) => {
                if (err || !asset) {
                    reject(err ?? new Error(`CCJsonLoader: asset not found at ${path}`));
                    return;
                }
                resolve((asset as JsonAsset).json as T);
            });
        });
    }
}
