const { Router } = require("express");
const { authMiddleware } = require("../middlewares/auth.middleware");
const { authorizeRoles } = require("../middlewares/role.middleware");
const upload = require("../middlewares/upload.middleware");
const { requireEnrollment } = require("../middlewares/enrollment.middleware");
const {
  createAssignment,
  getAssignmentsBySubject,
  getAssignmentsByLesson,
  deleteAssignment,
  getTeacherAssignments,
  getAssignmentById
} = require("../controllers/assignment.controller");

const assignmentRouter = Router();

// Create assignment (teacher only, optionally linked to a lesson)
assignmentRouter.post(
  "/create",
  authMiddleware,
  authorizeRoles("teacher"),
  upload.single("file"),
  createAssignment
);

assignmentRouter.get("/teacher", authMiddleware, getTeacherAssignments);

// Get all assignments by subject (students must be enrolled)
assignmentRouter.get(
  "/subject/:subjectId",
  authMiddleware,
  requireEnrollment({ allowTeacher: true }), // <-- enrollment check
  getAssignmentsBySubject
);

// Get all assignments for a specific lesson (students must be enrolled)
assignmentRouter.get(
  "/lesson/:lessonId",
  authMiddleware,
  requireEnrollment({ allowTeacher: true }), // <-- enrollment check
  getAssignmentsByLesson
);

assignmentRouter.get(
  "/assignment/:id",
  authMiddleware,
  requireEnrollment({ allowTeacher: true }),
  getAssignmentById
);

// Delete assignment (teacher or admin)
assignmentRouter.delete(
  "/delete/:id",
  authMiddleware,
  authorizeRoles("teacher", "admin"),
  deleteAssignment
);

module.exports = assignmentRouter;
