//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/labstack/echo/v5"
	"github.com/pocketbase/pocketbase"
	"github.com/pocketbase/pocketbase/apis"
	"github.com/pocketbase/pocketbase/core"
	"htwkalender/data-manager/service/db"
	"htwkalender/data-manager/service/ical"
	"io"
	"log/slog"
	"net/http"
)

func addFeedRoutes(app *pocketbase.PocketBase) {
	app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodPost,
			Path:   "/api/feed",
			Handler: func(c echo.Context) error {
				requestBody, _ := io.ReadAll(c.Request().Body)
				result, err := ical.CreateIndividualFeed(requestBody, app)
				if err != nil {
					slog.Error("Failed to create individual feed", "error", err)
					return c.JSON(http.StatusInternalServerError, "Failed to create individual feed")
				}
				return c.JSON(http.StatusOK, result)
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(app),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodDelete,
			Path:   "/api/feed",
			Handler: func(c echo.Context) error {
				token := c.QueryParam("token")
				err := db.DeleteFeed(app.Dao(), token)
				if err != nil {
					return c.JSON(http.StatusNotFound, err)
				} else {
					return c.JSON(http.StatusOK, "Feed deleted")
				}
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(app),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

}
