import { FileStore, S3Store } from '../tus';
import type { DataStore } from '../tus';
import { StorageType, StorageConfig } from '../types';

// 从环境变量获取存储配置
export function getStorageConfig(): StorageConfig {
	const storageType = (process.env.STORAGE_TYPE || 'local') as StorageType;

	console.log('=== 存储配置调试信息 ===');
	console.log('STORAGE_TYPE:', process.env.STORAGE_TYPE);
	console.log('实际存储类型:', storageType);
	console.log('S3_BUCKET:', process.env.S3_BUCKET);
	console.log('S3_ACCESS_KEY_ID:', process.env.S3_ACCESS_KEY_ID ? '已设置' : '未设置');
	console.log('S3_SECRET_ACCESS_KEY:', process.env.S3_SECRET_ACCESS_KEY ? '已设置' : '未设置');
	console.log('S3_ENDPOINT:', process.env.S3_ENDPOINT);
	console.log('S3_REGION:', process.env.S3_REGION);
	console.log('S3_FORCE_PATH_STYLE:', process.env.S3_FORCE_PATH_STYLE);
	console.log('========================');

	const config: StorageConfig = {
		type: storageType,
	};

	if (storageType === StorageType.LOCAL) {
		console.log('配置本地存储');
		const directory = process.env.LOCAL_STORAGE_DIRECTORY || process.env.UPLOAD_DIR || './uploads';
		console.log('本地存储目录:', directory);
		config.local = {
			directory,
			expirationPeriodInMilliseconds: 60 * 60 * 24 * 1000, // 默认24小时
		};
	} else if (storageType === StorageType.S3) {
		console.log('配置S3存储');
		config.s3 = {
			bucket: process.env.S3_BUCKET || 'uploads',
			region: process.env.S3_REGION || 'us-east-1',
			accessKeyId: process.env.S3_ACCESS_KEY_ID || 'minioadmin',
			secretAccessKey: process.env.S3_SECRET_ACCESS_KEY || 'minioadmin',
			endpoint: process.env.S3_ENDPOINT || 'http://localhost:9000',
			forcePathStyle: process.env.S3_FORCE_PATH_STYLE === 'true' || !process.env.S3_FORCE_PATH_STYLE, // MinIO默认需要路径样式
			partSize: parseInt(process.env.S3_PART_SIZE || '8388608'), // 8MB
			maxConcurrentPartUploads: parseInt(process.env.S3_MAX_CONCURRENT_UPLOADS || '6'),
			expirationPeriodInMilliseconds: 60 * 60 * 24 * 1000, // 默认24小时
		};

		console.log('S3 配置详情:');
		console.log('- Bucket:', config.s3.bucket || '❌ 未设置');
		console.log('- Region:', config.s3.region);
		console.log('- Access Key:', config.s3.accessKeyId ? '✅ 已设置' : '❌ 未设置');
		console.log('- Secret Key:', config.s3.secretAccessKey ? '✅ 已设置' : '❌ 未设置');
		console.log('- Endpoint:', config.s3.endpoint || '使用默认AWS端点');
	}

	return config;
}

// 验证存储配置
export function validateStorageConfig(config: StorageConfig): string[] {
	const errors: string[] = [];

	if (config.type === StorageType.LOCAL) {
		if (!config.local?.directory) {
			errors.push('Local storage directory is required');
		}
	} else if (config.type === StorageType.S3) {
		const s3Config = config.s3;
		if (!s3Config?.bucket) errors.push('S3 bucket is required');
		if (!s3Config?.region) errors.push('S3 region is required');
		if (!s3Config?.accessKeyId) errors.push('S3 access key ID is required');
		if (!s3Config?.secretAccessKey) errors.push('S3 secret access key is required');
	} else {
		errors.push(`Unsupported storage type: ${config.type}`);
	}

	return errors;
}

// 创建存储实例
export function createStorageInstance(config: StorageConfig): DataStore {
	// 验证配置
	const errors = validateStorageConfig(config);
	if (errors.length > 0) {
		throw new Error(`Storage configuration errors: ${errors.join(', ')}`);
	}

	switch (config.type) {
		case StorageType.LOCAL:
			return new FileStore({
				directory: config.local!.directory,
				expirationPeriodInMilliseconds: config.local!.expirationPeriodInMilliseconds,
			});

		case StorageType.S3:
			const s3Config = config.s3!;
			return new S3Store({
				partSize: s3Config.partSize,
				maxConcurrentPartUploads: s3Config.maxConcurrentPartUploads,
				expirationPeriodInMilliseconds: s3Config.expirationPeriodInMilliseconds,
				useTags: false, // 禁用标签功能，某些S3兼容服务不支持
				s3ClientConfig: {
					bucket: s3Config.bucket,
					region: s3Config.region,
					credentials: {
						accessKeyId: s3Config.accessKeyId,
						secretAccessKey: s3Config.secretAccessKey,
					},
					endpoint: s3Config.endpoint,
					forcePathStyle: s3Config.forcePathStyle,
				},
			});

		default:
			throw new Error(`Unsupported storage type: ${config.type}`);
	}
}

// 存储管理器类
export class StorageManager {
	private static instance: StorageManager;
	private storageConfig: StorageConfig;
	private dataStore: DataStore;

	private constructor() {
		this.storageConfig = getStorageConfig();
		this.dataStore = createStorageInstance(this.storageConfig);

		console.log(`Storage initialized: ${this.storageConfig.type}`);
		if (this.storageConfig.type === StorageType.LOCAL) {
			console.log(`Local directory: ${this.storageConfig.local?.directory}`);
		} else if (this.storageConfig.type === StorageType.S3) {
			console.log(`S3 bucket: ${this.storageConfig.s3?.bucket} in region: ${this.storageConfig.s3?.region}`);
		}
	}

	public static getInstance(): StorageManager {
		if (!StorageManager.instance) {
			StorageManager.instance = new StorageManager();
		}
		return StorageManager.instance;
	}

	public getDataStore(): DataStore {
		return this.dataStore;
	}

	public getStorageConfig(): StorageConfig {
		return this.storageConfig;
	}

	public getStorageType(): StorageType {
		return this.storageConfig.type;
	}

	// 切换存储类型（需要重启应用）
	public async switchStorage(newConfig: StorageConfig): Promise<void> {
		const errors = validateStorageConfig(newConfig);
		if (errors.length > 0) {
			throw new Error(`Invalid storage configuration: ${errors.join(', ')}`);
		}

		this.storageConfig = newConfig;
		this.dataStore = createStorageInstance(newConfig);

		console.log(`Storage switched to: ${newConfig.type}`);
	}

	// 获取存储统计信息
	public getStorageInfo() {
		return {
			type: this.storageConfig.type,
			config:
				this.storageConfig.type === StorageType.LOCAL
					? { directory: this.storageConfig.local?.directory }
					: {
							bucket: this.storageConfig.s3?.bucket,
							region: this.storageConfig.s3?.region,
							endpoint: this.storageConfig.s3?.endpoint,
						},
		};
	}
}
