import { StorageAdapter } from './StorageAdapter.js'
import { LocalAdapter } from './LocalAdapter.js'
import { OSSAdapter } from './OSSAdapter.js'

/**
 * 存储工厂类
 * 
 * 根据环境变量自动选择存储实现：
 * - STORAGE_TYPE=local: 使用LocalAdapter（本地文件系统）
 * - STORAGE_TYPE=oss: 使用OSSAdapter（阿里云OSS）
 * 
 * 零代码切换：
 * - 本地开发：不配置STORAGE_TYPE，默认使用local
 * - 云端部署：配置STORAGE_TYPE=oss，自动切换到OSS
 * 
 * @example
 * ```typescript
 * import { storage } from '@/common/storage'
 * 
 * // 业务代码不关心是local还是oss
 * const url = await storage.upload('literature/123.pdf', buffer)
 * ```
 */
export class StorageFactory {
  private static instance: StorageAdapter | null = null

  /**
   * 获取存储适配器实例（单例模式）
   */
  static getInstance(): StorageAdapter {
    if (!this.instance) {
      this.instance = this.createAdapter()
    }
    return this.instance
  }

  /**
   * 创建存储适配器
   */
  private static createAdapter(): StorageAdapter {
    const storageType = process.env.STORAGE_TYPE || 'local'

    switch (storageType) {
      case 'local':
        return this.createLocalAdapter()
      
      case 'oss':
        return this.createOSSAdapter()
      
      default:
        console.warn(`[StorageFactory] Unknown STORAGE_TYPE: ${storageType}, fallback to local`)
        return this.createLocalAdapter()
    }
  }

  /**
   * 创建本地适配器
   */
  private static createLocalAdapter(): LocalAdapter {
    const baseDir = process.env.LOCAL_STORAGE_DIR || 'uploads'
    const baseUrl = process.env.LOCAL_STORAGE_URL || 'http://localhost:3001/uploads'
    
    console.log(`[StorageFactory] Using LocalAdapter (baseDir: ${baseDir})`)
    
    return new LocalAdapter(baseDir, baseUrl)
  }

  /**
   * 创建OSS适配器
   */
  private static createOSSAdapter(): OSSAdapter {
    const region = process.env.OSS_REGION
    const bucket = process.env.OSS_BUCKET
    const accessKeyId = process.env.OSS_ACCESS_KEY_ID
    const accessKeySecret = process.env.OSS_ACCESS_KEY_SECRET

    // 验证必需的环境变量
    if (!region || !bucket || !accessKeyId || !accessKeySecret) {
      throw new Error(
        '[StorageFactory] OSS configuration incomplete. Required: OSS_REGION, OSS_BUCKET, OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET'
      )
    }

    console.log(`[StorageFactory] Using OSSAdapter (region: ${region}, bucket: ${bucket})`)

    return new OSSAdapter({
      region,
      bucket,
      accessKeyId,
      accessKeySecret
    })
  }

  /**
   * 重置实例（用于测试）
   */
  static reset(): void {
    this.instance = null
  }
}

