/**
 * Storage provider factory.
 *
 * Creates a StorageProvider based on STORAGE_PROVIDER env var or explicit type.
 * Defaults to 'azure' for backward compatibility.
 */

import { MemoryStorageProvider } from './providers/memory.js';
import type { StorageProvider, StorageProviderType } from './types.js';

let _provider: StorageProvider | null = null;

/**
 * Get the singleton storage provider.
 */
export async function getStorage(): Promise<StorageProvider> {
  if (!_provider) {
    const providerType = (process.env.STORAGE_PROVIDER || 'azure') as StorageProviderType;
    _provider = await createStorageProvider(providerType);
  }
  return _provider;
}

/**
 * Create a storage provider by type.
 */
export async function createStorageProvider(type: StorageProviderType): Promise<StorageProvider> {
  switch (type) {
    case 'azure': {
      const { AzureBlobStorageProvider } = await import('./providers/azure-blob.js');
      return new AzureBlobStorageProvider();
    }
    case 'memory':
      return new MemoryStorageProvider();
    default:
      throw new Error(`Unknown STORAGE_PROVIDER: '${type}'. Valid: azure, memory`);
  }
}

/**
 * Set the singleton storage provider (for testing).
 */
export function setStorage(provider: StorageProvider): void {
  _provider = provider;
}

/**
 * @internal
 */
export function _resetStorage(): void {
  _provider = null;
}
