const express = require('express');
const router = express.Router();
const {createCar, getCollection} = require('../../controllers/collectionController');
const multer = require("multer");
const path = require("path");
const authMiddleware = require('../../middleware/authMiddleware');

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    // Ensure this directory exists on disk: "./uploads/cars"
    cb(null, path.join(__dirname, "../../../uploads/cars"));
  },
  filename: (req, file, cb) => {
    let ext = ".jpg";
    if (file.mimetype === "image/png") ext = ".png";
    else if (file.mimetype === "image/jpeg") ext = ".jpg";

    // Use a timestamp as filename: e.g. "1627890123456.png"
    cb(null, `${Date.now()}${ext}`);
  },
});


const allowedMimeTypes = new Set(["image/jpeg", "image/png", "image/jpg"]);

const upload = multer({
  storage,
  limits: { fileSize: 5 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    if (!allowedMimeTypes.has(file.mimetype)) {
      return cb(new Error("Only JPG/JPEG/PNG images are allowed"), false);
    }
    cb(null, true);
  },
});

router.post('/addCar', authMiddleware, upload.single("image"), createCar);

router.get('/getCollection', authMiddleware, getCollection);

module.exports = router;