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 inspectionReportPhotoUploadConfig: MulterOptions = {
  storage: diskStorage({
    destination: (req, file, cb) => {
      const uploadPath = `./public/${fileStoreLocation.inspection_report_photos}`
      createFolderIfNotExist(uploadPath)
      cb(null, uploadPath)
    },
    filename: (req, file, cb) => {
      const timestamp = Date.now()
      const originalFilename = file.originalname
      const fileExtension = originalFilename.split(".").pop()
      const photoType = file.fieldname.replace(/_/g, "-") // e.g., front_side_photo -> front-side-photo
      const sanitizedFileNameWithoutExtension = photoType
        .replace(/\s+/g, "-") // Replace spaces with hyphens
        .replace(/[^a-zA-Z0-9-_.]/g, "_") // Replace special characters with underscores

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