const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const companyController = require("../../controllers/college/companyController");

const dir = path.join(__dirname, "..", "uploads", "companies");
if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir, { recursive: true });
}

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, "uploads/companies/"),
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  },
});

const upload = multer({
  storage,
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith("image/")) cb(null, true);
    else cb(new Error("Only image files are allowed!"), false);
  },
  limits: { fileSize: 5 * 1024 * 1024 },
});

router.get("/", companyController.getAllCompanies);
router.post("/", upload.single("image"), companyController.createCompany);
router.put("/:id", upload.single("image"), companyController.updateCompany);
router.delete("/:id", companyController.deleteCompany);

module.exports = router;
