package handlers import ( "Rezina-Backend/internal/domain" "Rezina-Backend/internal/services/examprep" "errors" "fmt" "strconv" "github.com/gofiber/fiber/v2" ) // CreateExamPrepUnit godoc // @Summary Create chapter // @Description Chapter under a course (e.g. chapter title). Optional sort_order assigns position within that course (siblings at or after that index are shifted); omit to append after the current highest sort_order in the course. // @Tags learning // @Accept json // @Produce json // @Param courseId path int true "Course ID" // @Param body body domain.CreateExamPrepUnitInput true "Chapter" // @Success 201 {object} domain.Response{data=domain.ExamPrepUnit} // @Router /api/v1/admin/courses/{courseId}/chapters [post] // @Security Bearer // @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 404 {object} domain.ErrorResponse "Resource not found" // @Failure 500 {object} domain.ErrorResponse "Internal server error" func (h *Handler) CreateExamPrepUnit(c *fiber.Ctx) error { catalogCourseID, err := strconv.ParseInt(c.Params("courseId"), 10, 64) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid course id", Error: err.Error(), }) } var req domain.CreateExamPrepUnitInput if err := c.BodyParser(&req); err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid request body", Error: err.Error(), }) } if valErrs, ok := h.validator.Validate(c, req); !ok { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Validation failed", Error: firstValidationError(valErrs), }) } out, err := h.examPrepSvc.CreateUnit(c.Context(), catalogCourseID, req) if err != nil { if errors.Is(err, examprep.ErrCatalogCourseNotFound) { return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ Message: "Course not found", Error: err.Error(), }) } return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to create chapter", Error: err.Error(), }) } h.recordActivity(c, domain.ActionExamPrepUnitCreated, domain.ResourceExamPrepUnit, &out.ID, "Created chapter: "+out.Name, nil) return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Chapter created successfully", Data: out, Success: true, StatusCode: fiber.StatusCreated, }) } // ListExamPrepUnitsByCatalogCourse godoc // @Summary List chapters for a course // @Tags learning // @Param courseId path int true "Course ID" // @Param limit query int false "Page size" default(20) // @Param offset query int false "Offset" default(0) // @Success 200 {object} domain.Response{data=chapterListData} // @Router /api/v1/admin/courses/{courseId}/chapters [get] // @Router /api/v1/courses/{courseId}/chapters [get] // @Security Bearer // @Produce json // @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 404 {object} domain.ErrorResponse "Resource not found" // @Failure 500 {object} domain.ErrorResponse "Internal server error" func (h *Handler) ListExamPrepUnitsByCatalogCourse(c *fiber.Ctx) error { catalogCourseID, err := strconv.ParseInt(c.Params("courseId"), 10, 64) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid course id", Error: err.Error(), }) } limit, _ := strconv.Atoi(c.Query("limit", "20")) offset, _ := strconv.Atoi(c.Query("offset", "0")) publishedOnly := !h.canManageExamPrepUnits(c) if publishedOnly { // Draft courses hide their units from non-managers. cc, err := h.examPrepSvc.GetCatalogCourseByID(c.Context(), catalogCourseID) if err == nil && !cc.VisibleToLearners() { return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ Message: "Course not found", Error: examprep.ErrCatalogCourseNotFound.Error(), }) } } items, total, err := h.examPrepSvc.ListUnitsByCatalogCourse(c.Context(), catalogCourseID, publishedOnly, int32(limit), int32(offset)) if err != nil { if errors.Is(err, examprep.ErrCatalogCourseNotFound) { return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ Message: "Course not found", Error: err.Error(), }) } return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to list units", Error: err.Error(), }) } if err := h.annotateExamPrepUnitsEffectiveAccessTier(c.Context(), c.Locals("role").(domain.Role), catalogCourseID, items); err != nil { if status, msg := mapExamPrepEffectiveAccessTierError(err); status != 0 { return c.Status(status).JSON(domain.ErrorResponse{Message: msg, Error: err.Error()}) } } if err := h.applyExamPrepAccessUnits(c.Context(), c, items); err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to build unit list", Error: err.Error(), }) } return c.JSON(domain.Response{ Message: "Chapters retrieved successfully", Data: fiber.Map{ "chapters": items, "total_count": total, "limit": limit, "offset": offset, }, Success: true, StatusCode: fiber.StatusOK, }) } // ReorderExamPrepUnitsInCatalogCourse godoc // @Summary Reorder chapters within a course // @Tags learning // @Param courseId path int true "Course ID" // @Param body body domain.ReorderIDsRequest true "ordered_ids: every chapter id in this course, new order" // @Router /api/v1/admin/courses/{courseId}/chapters/reorder [put] // @Security Bearer // @Success 200 {object} MessageResponse // @Produce json // @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 404 {object} domain.ErrorResponse "Resource not found" // @Failure 500 {object} domain.ErrorResponse "Internal server error" func (h *Handler) ReorderExamPrepUnitsInCatalogCourse(c *fiber.Ctx) error { catalogCourseID, err := strconv.ParseInt(c.Params("courseId"), 10, 64) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid course id", Error: err.Error(), }) } var req domain.ReorderIDsRequest if err := c.BodyParser(&req); err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid request body", Error: err.Error(), }) } if req.OrderedIDs == nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "ordered_ids is required (use an empty array if there are no units)", Error: "missing ordered_ids", }) } if err := h.examPrepSvc.ReorderUnitsInCatalogCourse(c.Context(), catalogCourseID, req.OrderedIDs); err != nil { if errors.Is(err, examprep.ErrCatalogCourseNotFound) { return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ Message: "Course not found", Error: err.Error(), }) } if errors.Is(err, domain.ErrReorderInvalidIDSet) { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: err.Error(), Error: "INVALID_REORDER", }) } return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to reorder units", Error: err.Error(), }) } h.recordActivity(c, domain.ActionExamPrepUnitReordered, domain.ResourceExamPrepUnit, &catalogCourseID, "Reordered chapters in course", nil) return c.JSON(domain.Response{ Message: "Units reordered successfully", Success: true, StatusCode: fiber.StatusOK, }) } // GetExamPrepUnitByID godoc // @Summary Get chapter by ID // @Tags learning // @Param id path int true "Chapter ID" // @Router /api/v1/admin/chapters/{id} [get] // @Router /api/v1/chapters/{id} [get] // @Security Bearer // @Success 200 {object} domain.Response{data=domain.ExamPrepUnit} // @Produce json // @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 404 {object} domain.ErrorResponse "Resource not found" // @Failure 500 {object} domain.ErrorResponse "Internal server error" func (h *Handler) GetExamPrepUnitByID(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid chapter id", Error: err.Error(), }) } out, err := h.examPrepSvc.GetUnitByID(c.Context(), id) if err != nil { if errors.Is(err, examprep.ErrUnitNotFound) { return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ Message: "Chapter not found", Error: err.Error(), }) } return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to get unit", Error: err.Error(), }) } if !out.VisibleToLearners() && !h.canManageExamPrepUnits(c) { return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ Message: "Chapter not found", Error: examprep.ErrUnitNotFound.Error(), }) } if err := h.annotateExamPrepUnitEffectiveAccessTier(c.Context(), c.Locals("role").(domain.Role), &out); err != nil { if status, msg := mapExamPrepEffectiveAccessTierError(err); status != 0 { return c.Status(status).JSON(domain.ErrorResponse{Message: msg, Error: err.Error()}) } } if err := h.applyExamPrepAccessUnit(c.Context(), c, &out); err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to build unit", Error: err.Error(), }) } return c.JSON(domain.Response{ Message: "Unit retrieved successfully", Data: out, Success: true, StatusCode: fiber.StatusOK, }) } // UpdateExamPrepUnit godoc // @Summary Update chapter // @Tags learning // @Param id path int true "Chapter ID" // @Param body body domain.UpdateExamPrepUnitInput true "Fields to update" // @Router /api/v1/admin/chapters/{id} [put] // @Security Bearer // @Success 200 {object} domain.Response{data=domain.ExamPrepUnit} // @Produce json // @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 404 {object} domain.ErrorResponse "Resource not found" // @Failure 500 {object} domain.ErrorResponse "Internal server error" func (h *Handler) UpdateExamPrepUnit(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid chapter id", Error: err.Error(), }) } var req domain.UpdateExamPrepUnitInput if err := c.BodyParser(&req); err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid request body", Error: err.Error(), }) } out, err := h.examPrepSvc.UpdateUnit(c.Context(), id, req) if err != nil { if errors.Is(err, examprep.ErrUnitNotFound) { return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ Message: "Chapter not found", Error: err.Error(), }) } return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to update unit", Error: err.Error(), }) } h.recordActivity(c, domain.ActionExamPrepUnitUpdated, domain.ResourceExamPrepUnit, &out.ID, "Updated chapter: "+out.Name, nil) return c.JSON(domain.Response{ Message: "Chapter updated successfully", Data: out, Success: true, StatusCode: fiber.StatusOK, }) } // DeleteExamPrepUnit godoc // @Summary Delete chapter // @Tags learning // @Param id path int true "Chapter ID" // @Router /api/v1/admin/chapters/{id} [delete] // @Security Bearer // @Success 200 {object} MessageResponse // @Produce json // @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 404 {object} domain.ErrorResponse "Resource not found" // @Failure 500 {object} domain.ErrorResponse "Internal server error" func (h *Handler) DeleteExamPrepUnit(c *fiber.Ctx) error { id, err := strconv.ParseInt(c.Params("id"), 10, 64) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid chapter id", Error: err.Error(), }) } if err := h.examPrepSvc.DeleteUnit(c.Context(), id); err != nil { if errors.Is(err, examprep.ErrUnitNotFound) { return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ Message: "Chapter not found", Error: err.Error(), }) } return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to delete unit", Error: err.Error(), }) } h.recordActivity(c, domain.ActionExamPrepUnitDeleted, domain.ResourceExamPrepUnit, &id, fmt.Sprintf("Deleted chapter ID: %d", id), nil) return c.JSON(domain.Response{ Message: "Chapter deleted successfully", Success: true, StatusCode: fiber.StatusOK, }) }