import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';

@Injectable()
export class LocalStorageAdapter {
  private readonly uploadPath = process.env.UPLOAD_PATH || 'public/upload';

  async save(file: Express.Multer.File, filename: string): Promise<string> {
    const uploadDir = path.join(process.cwd(), this.uploadPath);
    
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }

    const filePath = path.join(uploadDir, filename);
    fs.writeFileSync(filePath, file.buffer);

    return `/upload/${filename}`;
  }

  async delete(filename: string): Promise<void> {
    const filePath = path.join(process.cwd(), this.uploadPath, filename);
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
    }
  }

  async exists(filename: string): Promise<boolean> {
    const filePath = path.join(process.cwd(), this.uploadPath, filename);
    return fs.existsSync(filePath);
  }
}
