import { extname } from 'path';
import { v4 as uuidv4 } from 'uuid';
import { HttpException, HttpStatus } from '@nestjs/common';
import * as fs from 'fs';
import { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface';
import { diskStorage } from 'multer';

const MB = 1024 * 1024;

const fileFilter = (req, file, callback) => {
  if (
    file.mimetype.match(/\/(jpg|jpeg|png|flv|mp4|m3u8|ts|3gp|mov|avi|wmv)$/)
  ) {
    callback(null, true);
  } else {
    callback(
      new HttpException(
        `Unsupported file type ${extname(file.originalname)}`,
        HttpStatus.BAD_REQUEST,
      ),
      false,
    );
  }
};

const editFileName = (req, file, callback) => {
  const fileExtName = extname(file.originalname);
  const randomName = uuidv4();
  callback(null, `${randomName}${fileExtName}`);
};

const destinationPath = (req, file, cb) => {
  let modulePath = req.body.module;
  if (req.body.sub_module) modulePath = `${modulePath}/${req.body.sub_module}`;

  fs.mkdirSync(`./uploads/tmp/${modulePath}`, { recursive: true });
  cb(null, `./uploads/tmp/${modulePath}`);
};

export const StoreFileConfig: MulterOptions = {
  storage: diskStorage({
    destination: destinationPath,
    filename: editFileName,
  }),
  fileFilter: fileFilter,
};
