import multer from "multer";
import path from "path";

/** Memory storage — files are uploaded to Cloudflare R2 after multer. */
export const s3Storage = multer.memoryStorage();

export const handleMediaFiles = multer({
  storage: s3Storage,
  limits: {
    fileSize: 1024 * 1024 * 100,
  },
  fileFilter: (req, file, callback) => {
    const FileTypes = /jpeg|jpg|png|gif|mp4|mpeg/;
    const isValidFile = FileTypes.test(
      path.extname(file.originalname).toLowerCase(),
    );

    if (isValidFile) {
      callback(null, true);
    } else {
      callback(new Error("File type not supported") as any, false);
    }
  },
});

/**
 * Image uploads (gas station, trips, profile).
 * Uses memory storage; controllers must call R2 upload helpers.
 */
export const handleMediaFilesLocal = multer({
  storage: s3Storage,
  limits: {
    fileSize: 1024 * 1024 * 100,
  },
  fileFilter: (req, file, callback) => {
    try {
      const allowedExt = /jpeg|jpg|png|jfif|webp/i;
      const allowedMime = /^image\/(jpeg|jpg|png|pjpeg|jfif|webp)$/i;
      const mimType = allowedMime.test(file.mimetype);
      const extname = allowedExt.test(
        path.extname(file.originalname).toLowerCase(),
      );
      if (mimType && extname) {
        return callback(null, true);
      }
      return callback(
        new Error(
          "File type not supported. Allowed: jpg, jpeg, png, jfif, webp",
        ) as any,
        false,
      );
    } catch (error: any) {
      return callback(new Error(error.message) as any, false);
    }
  },
});

/** Chat attachments: images + short videos (max 25MB per file, up to 10 files). */
export const handleChatMediaLocal = multer({
  storage: s3Storage,
  limits: {
    fileSize: 1024 * 1024 * 25,
    files: 10,
  },
  fileFilter: (_req, file, callback) => {
    try {
      const allowedExt = /jpeg|jpg|png|jfif|webp|gif|mp4|mov|webm/i;
      const allowedMime =
        /^(image\/(jpeg|jpg|png|pjpeg|jfif|webp|gif)|video\/(mp4|quicktime|webm))$/i;
      const mimType = allowedMime.test(file.mimetype);
      const extname = allowedExt.test(
        path.extname(file.originalname).toLowerCase(),
      );
      if (mimType && extname) {
        return callback(null, true);
      }
      return callback(
        new Error(
          "File type not supported. Allowed: jpg, jpeg, png, webp, gif, mp4, mov, webm",
        ) as any,
        false,
      );
    } catch (error: any) {
      return callback(new Error(error.message) as any, false);
    }
  },
});
