import { diskStorage } from "multer"
import { BadRequestException } from "@nestjs/common"
import * as path from "path"
import { createFolderIfNotExist, validationMessage } from "../../utils/helpers"
import { fileStoreLocation } from "./file-store-location"
import { code } from "../response/response.code"
import { messageKey } from "../../constants/message-keys"

// Combined Multer config
export const customerUploadConfig = {
  storage: diskStorage({
    destination: (req, file, cb) => {
      let uploadPath: string

      if (file.fieldname === "profile_photo") {
        uploadPath = `./public/${fileStoreLocation.customer_profile_photo}`
      } else if (file.fieldname === "letter_of_guarantee") {
        uploadPath = `./public/${fileStoreLocation.letter_of_guarantee}`
      } else {
        uploadPath = "./public/misc"
      }

      createFolderIfNotExist(uploadPath)
      cb(null, uploadPath)
    },
    filename: (req, file, cb) => {
      const ext = path.extname(file.originalname)
      const base = path.basename(file.originalname, ext)
      const timestamp = Date.now()
      cb(null, `${base}-${timestamp}${ext}`)
    },
  }),
  fileFilter: (req, file, cb) => {
    if (file.fieldname === "profile_photo") {
      if (!/\.(jpg|jpeg|png|webp)$/i.test(file.originalname)) {
        return cb(
          new BadRequestException({
            statusCode: code.VALIDATION,
            message: validationMessage(messageKey.invalid_file_type, {
              file_types: "jpg, jpeg, png, webp",
            }),
          }),
          false,
        )
      }
    } else if (file.fieldname === "letter_of_guarantee") {
      if (!/\.pdf$/i.test(file.originalname)) {
        return cb(
          new BadRequestException({
            statusCode: code.VALIDATION,
            message: validationMessage(messageKey.invalid_file_type, {
              file_types: "pdf",
            }),
          }),
          false,
        )
      }
    }
    cb(null, true)
  },
  limits: {
    // max file size to cover both fields
    fileSize: Math.max(5 * 1024 * 1024, 20 * 1024 * 1024),
  },
}
