const multer = require('multer')
const path = require('path')
const CustomError = require('../errors')
const fs = require('fs')
const dirExist = require('./dirExist')
const createDir = require('./createDir')

//Destination to store the file
const fileStorage = multer.diskStorage({
    destination: function (req, file, cb) { 

        const dir = path.join(process.cwd(), 'public', 'jsonfiles')

        if (!dirExist(dir)) {
            createDir(dir)
        }

        cb(null, dir)
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + String(Math.floor(Math.random() * 1000)) + path.extname(file.originalname))
    }
})

const fileUpload = multer({
    storage: fileStorage,
    fileFilter(req, file, cb) {

        if (!file.originalname.match(/\.(json)$/i)) {
            return cb(new CustomError.BadRequestError(`'Invalid file type. Send only .json file!`))

        }
        cb(undefined, true)


    }

})

module.exports = fileUpload 