//Calendar implementation for the HTWK Leipzig timetable. Evaluation and display of the individual dates in iCal format.
//Copyright (C) 2024 HTWKalender support@htwkalender.de

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU Affero General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU Affero General Public License for more details.

//You should have received a copy of the GNU Affero General Public License
//along with this program.  If not, see <https://www.gnu.org/licenses/>.

package service

import (
	"github.com/pocketbase/pocketbase"
	"github.com/pocketbase/pocketbase/core"
	"htwkalender/data-manager/model"
	"htwkalender/data-manager/service/feed"
	"htwkalender/data-manager/service/ical"
	"log/slog"
	"net/http"
)

func addFeedRoutes(se *core.ServeEvent, pb *pocketbase.PocketBase) {
	se.Router.POST("/api/feed", func(e *core.RequestEvent) error {
		var feedCollection []model.FeedCollection
		err := e.BindBody(&feedCollection)
		if err != nil {
			slog.Error("Failed to bind request body", "error", err)
			return e.JSON(http.StatusBadRequest, "Invalid request body")
		}
		result, err := ical.CreateIndividualFeed(feedCollection, pb)
		if err != nil {
			slog.Error("Failed to create individual feed", "error", err)
			return e.JSON(http.StatusInternalServerError, "Failed to create individual feed")
		}
		return e.JSON(http.StatusOK, result)
	})

	se.Router.DELETE("/api/feed", func(e *core.RequestEvent) error {
		token := e.Request.URL.Query().Get("token")
		err := feed.MarkFeedForDeletion(pb, token)
		if err != nil {
			return e.JSON(http.StatusNotFound, err)
		} else {
			return e.JSON(http.StatusOK, "Feed deleted")
		}
	})

}
