package professor

import (
	"htwkalender/data-manager/model"
	"htwkalender/data-manager/service/ical"
	"log/slog"
	"net/http"

	"github.com/pocketbase/pocketbase/apis"
	"github.com/pocketbase/pocketbase/core"
)

func RegisterRoutes(se *core.ServeEvent, service *ProfessorService) {
	se.Router.GET("/api/professor/modules", func(e *core.RequestEvent) error {
		record := e.Auth
		if record == nil {
			return apis.NewForbiddenError("Only authenticated users can access this endpoint", nil)
		}

		email := record.GetString("email")
		if email == "" {
			return apis.NewBadRequestError("User has no email", nil)
		}

		modules, err := service.GetModulesForProfessor(email)
		if err != nil {
			return apis.NewBadRequestError("Failed to fetch modules", err)
		}

		return e.JSON(http.StatusOK, modules)
	}).Bind(apis.RequireAuth())

	// POST /api/professor/feed - Create a professor-specific feed
	se.Router.POST("/api/professor/feed", func(e *core.RequestEvent) error {
		record := e.Auth
		if record == nil {
			return apis.NewForbiddenError("Only authenticated users can access this endpoint", nil)
		}

		userId := record.Id
		if userId == "" {
			return apis.NewBadRequestError("User ID not found", nil)
		}

		// Bind the feed collection from request body
		var feedCollection []model.FeedCollection
		err := e.BindBody(&feedCollection)
		if err != nil {
			slog.Error("Failed to bind request body", "error", err)
			return apis.NewBadRequestError("Invalid request body", err)
		}

		// Create feed with type="prof" and link to authenticated user
		token, err := ical.CreateIndividualFeedWithType(feedCollection, "prof", userId, service.app)
		if err != nil {
			slog.Error("Failed to create professor feed", "error", err, "userId", userId)
			return apis.NewInternalServerError("Failed to create professor feed", err)
		}

		slog.Info("Created professor feed", "userId", userId, "token", token)
		return e.JSON(http.StatusOK, token)
	}).Bind(apis.RequireAuth())
}
