import express from "express";
import * as ctrl from "../controllers/applications.controller.js";
import { uploadSingle } from "../middlewares/upload.js";
import { errorResponse } from "../utils/response.js";
import { HTTP_STATUS } from "../constants/index.js";

const router = express.Router();

// Error handling middleware for multer
const handleMulterError = (err, req, res, next) => {
  if (err) {
    console.error("Multer error:", err);
    if (err.code === "LIMIT_FILE_SIZE") {
      return errorResponse(res, "File size too large. Maximum size is 10MB.", HTTP_STATUS.BAD_REQUEST);
    }
    if (err.code === "LIMIT_UNEXPECTED_FILE") {
      return errorResponse(res, "Unexpected file field. Please use 'cv' as the field name.", HTTP_STATUS.BAD_REQUEST);
    }
    if (err.message) {
      return errorResponse(res, err.message, HTTP_STATUS.BAD_REQUEST);
    }
    return errorResponse(res, "File upload error", HTTP_STATUS.BAD_REQUEST);
  }
  next();
};

router.get("/", ctrl.list);
router.get("/:id", ctrl.getById);
// POST with file upload middleware
router.post("/", (req, res, next) => {
  uploadSingle(req, res, (err) => {
    if (err) {
      return handleMulterError(err, req, res, next);
    }
    next();
  });
}, ctrl.create);
router.put("/:id", ctrl.update);
router.delete("/:id", ctrl.remove);

export default router;

