import { diskStorage } from "multer"
import { MulterOptions } from "@nestjs/platform-express/multer/interfaces/multer-options.interface"
import { BadRequestException } from "@nestjs/common"
import { code } from "../response/response.code"
import { createFolderIfNotExist, validationMessage } from "../../utils/helpers"
import { messageKey } from "../../constants/message-keys"
import { fileStoreLocation } from "./file-store-location"

export const profilePicConfig: MulterOptions = {
  storage: diskStorage({
    destination: (req, file, cb) => {
      const uploadPath = `./public/${fileStoreLocation.profile_pic}`
      createFolderIfNotExist(uploadPath)
      cb(null, uploadPath)
    },
    filename: (req, file, cb) => {
      const timestamp = Date.now()
      const originalFilename = file.originalname
      const fileExtension = originalFilename.split(".").pop()
      const fileNameWithoutExtension = originalFilename.replace(
        `.${fileExtension}`,
        "",
      )
      const sanitizedFileNameWithoutExtension = fileNameWithoutExtension
        .replace(/\s+/g, "-") // Replace spaces with hyphens
        .replace(/[^a-zA-Z0-9-_.]/g, "_") // Replace special characters with underscores

      const newFilename = `${sanitizedFileNameWithoutExtension}-${timestamp}.${fileExtension}`
      return cb(null, newFilename)
    },
  }),
  limits: {
    fileSize: 20 * 1024 * 1024,
  },
  fileFilter: (req, file, cb) => {
    if (!file.originalname.match(/\.(jpg|jpeg|png|webp)$/)) {
      return cb(
        new BadRequestException({
          statusCode: code.VALIDATION,
          message: validationMessage(messageKey.invalid_file_type, {
            file_types: "jpg, jpeg, png, webp",
          }),
        }),
        false,
      )
    }
    cb(null, true)
  },
}
