const express = require('express');
const router = express.Router();
const { createPost, getPosts, getLatestPosts } = require('../../controllers/postsController');
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/posts"
    cb(null, path.join(__dirname, "../../../uploads/posts"));
  },
  filename: (req, file, cb) => {
    let ext = ".jpg";
    if (file.mimetype === "image/png") ext = ".png";
    else if (file.mimetype === "image/jpeg") ext = ".jpg";

    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('/createPost', authMiddleware, upload.single("image"), createPost);

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

router.get('/getLatestPosts', getLatestPosts);

module.exports = router;