import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as fs from 'fs';
import * as path from 'path';

@Injectable()
export class LocalStorageAdapter {
  private readonly logger = new Logger(LocalStorageAdapter.name);
  private readonly tempDir: string;

  constructor(private readonly configService: ConfigService) {
    this.tempDir = this.configService.get<string>('SNAPSHOT_TEMP_DIR', './data/snapshots');
    fs.mkdirSync(this.tempDir, { recursive: true });
    this.logger.log(`Local storage adapter configured: ${this.tempDir}`);
  }

  getTaskDir(taskId: string): string {
    const taskDir = path.join(this.tempDir, taskId);
    fs.mkdirSync(taskDir, { recursive: true });
    return taskDir;
  }

  getFilePath(taskId: string, fileName: string): string {
    return path.join(this.tempDir, taskId, fileName);
  }

  fileExists(taskId: string, fileName: string): boolean {
    return fs.existsSync(this.getFilePath(taskId, fileName));
  }

  deleteTask(taskId: string): void {
    const taskDir = path.join(this.tempDir, taskId);
    if (fs.existsSync(taskDir)) {
      fs.rmSync(taskDir, { recursive: true, force: true });
      this.logger.log(`Deleted local snapshot: ${taskDir}`);
    }
  }

  /** 列出临时目录中所有任务子目录的 ID */
  listTaskDirs(): string[] {
    if (!fs.existsSync(this.tempDir)) return [];
    return fs.readdirSync(this.tempDir, { withFileTypes: true })
      .filter((e) => e.isDirectory())
      .map((e) => e.name);
  }

  cleanupExpired(retentionHours: number): string[] {
    const threshold = Date.now() - retentionHours * 60 * 60 * 1000;
    const deletedIds: string[] = [];

    if (!fs.existsSync(this.tempDir)) return deletedIds;

    const entries = fs.readdirSync(this.tempDir, { withFileTypes: true });
    for (const entry of entries) {
      if (!entry.isDirectory()) continue;

      const dirPath = path.join(this.tempDir, entry.name);
      const stat = fs.statSync(dirPath);

      if (stat.mtimeMs < threshold) {
        fs.rmSync(dirPath, { recursive: true, force: true });
        deletedIds.push(entry.name);
        this.logger.log(`Cleaned up expired snapshot: ${entry.name}`);
      }
    }

    return deletedIds;
  }
}
