import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import {
  DRACOLoader,
  DRACO_GLTF_CONFIG,
} from 'three/examples/jsm/loaders/DRACOLoader.js';
import { KTX2Loader } from 'three/examples/jsm/loaders/KTX2Loader.js';

export interface ViewerLoaders {
  gltf: GLTFLoader;
  draco: DRACOLoader;
  ktx2: KTX2Loader;
}

// 여러 DRACOLoader/KTX2Loader instance를 만들면 충돌할 수 있으므로 하나를 공유합니다.
// decoder URL은 Three.js import가 생성하는 version 일치 hashed asset을 사용합니다.
let _cache: ViewerLoaders | null = null;

export function getLoaders(renderer: THREE.WebGLRenderer): ViewerLoaders {
  if (_cache) return _cache;
  const draco = new DRACOLoader().setDecoderPath(DRACO_GLTF_CONFIG);
  const ktx2 = new KTX2Loader().detectSupport(renderer);
  const gltf = new GLTFLoader().setDRACOLoader(draco).setKTX2Loader(ktx2);
  _cache = { gltf, draco, ktx2 };
  return _cache;
}
