import express from "express";
import * as ctrl from "../controllers/userResume.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();
};

// GET /api/user-resumes - Get all user resumes
router.get("/", ctrl.list);

// POST /api/user-resumes - Create a new user resume (with file upload)
// Note: multer errors are automatically passed to error handler, but we catch them explicitly
router.post("/", (req, res, next) => {
  uploadSingle(req, res, (err) => {
    if (err) {
      return handleMulterError(err, req, res, next);
    }
    next();
  });
}, ctrl.create);

export default router;

