import { IStorageProvider } from './IStorageProvider';
import { LocalStorageAdapter } from './LocalStorageAdapter';
import { MinioStorageAdapter } from './MinioStorageAdapter';

let _instance: IStorageProvider | null = null;
let _instanceProvider: string | null = null;

/**
 * Returns the configured storage adapter based on the STORAGE_PROVIDER env variable.
 * The adapter instance is cached (singleton) so MinIO client connections are reused across requests.
 * Defaults to 'local' when not set.
 */
export function getStorageAdapter(): IStorageProvider {
	const provider = (process.env.STORAGE_PROVIDER || 'local').toLowerCase();

	if (_instance && _instanceProvider === provider) {
		return _instance;
	}

	switch (provider) {
		case 'minio':
			_instance = new MinioStorageAdapter();
			break;
		case 'local':
		default:
			_instance = new LocalStorageAdapter();
			break;
	}
	_instanceProvider = provider;
	return _instance;
}

/** Reset the cached adapter instance — for testing only. */
export function _resetStorageInstance(): void {
	_instance = null;
	_instanceProvider = null;
}
