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

@Injectable()
export class MultimediaService {
  generateRandomName(extension: string): string {
    const randomStr = Math.random().toString(36).substring(2, 12);
    const timestamp = Date.now();
    return `${timestamp}-${randomStr}.${extension}`;
  }

  async saveImage(
    file: Express.Multer.File,
    originalsPath: string,
    name: string = 'default.jpg',
  ) {
    const ext = path.extname(file.originalname).replace('.', '') || 'jpg';
    const newFileName = this.generateRandomName(ext);
    const originalFullPath = path.join(originalsPath, newFileName);

    await fsp.writeFile(originalFullPath, file.buffer);
    await this.removeImage(originalsPath, name);
    return newFileName;
  }

  async removeImage(path: string, name: string) {
    try {
      if (name !== 'default.jpg') {
        await fsp.unlink(path + name);
      }
    } catch (err: any) {
      console.error(`Error al eliminar ${path}: ${err}`);
    }
  }
}
