//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 (
	"htwkalender/data-manager/model/serviceModel"
	"htwkalender/data-manager/service/course"
	"htwkalender/data-manager/service/fetch/sport"
	v1 "htwkalender/data-manager/service/fetch/v1"
	v2 "htwkalender/data-manager/service/fetch/v2"
	"htwkalender/data-manager/service/functions/time"
	"htwkalender/data-manager/service/room"
	"log/slog"
	"net/http"

	"github.com/labstack/echo/v5"
	"github.com/pocketbase/pocketbase/apis"
	"github.com/pocketbase/pocketbase/core"
)

func AddRoutes(services serviceModel.Service) {

	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/fetch/events",
			Handler: func(c echo.Context) error {
				savedEvents, err := v2.ParseEventsFromRemote(services.App)
				if err != nil {
					slog.Error("Failed to parse events from remote: ", "error", err)
					return c.JSON(http.StatusBadRequest, "Failed to parse events from remote")
				} else {
					return c.JSON(http.StatusOK, savedEvents)
				}
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
				apis.RequireAdminAuth(),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/fetch/daily/events",
			Handler: func(c echo.Context) error {
				course.UpdateCourse(services)
				return c.JSON(http.StatusOK, "Daily events fetched")
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
				apis.RequireAdminAuth(),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/fetch/groups",
			Handler: func(c echo.Context) error {
				groups, err := v1.FetchSeminarGroups(services.App)
				if err != nil {
					return c.JSON(http.StatusBadRequest, "Failed to fetch seminar groups")
				}
				return c.JSON(http.StatusOK, groups)
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
				apis.RequireAdminAuth(),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/fetch/sports",
			Handler: func(c echo.Context) error {

				sportEvents, err := sport.FetchAndUpdateSportEvents(services.App)
				if err != nil {
					return c.JSON(http.StatusBadRequest, "Failed to fetch sport events")
				}
				return c.JSON(http.StatusOK, sportEvents)
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
				apis.RequireAdminAuth(),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodDelete,
			Path:   "/api/modules",
			Handler: func(c echo.Context) error {
				err := services.EventService.DeleteAllEvents()
				if err != nil {
					return c.JSON(http.StatusBadRequest, "Failed to delete events")
				}
				return c.JSON(http.StatusOK, "Events deleted")
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
				apis.RequireAdminAuth(),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/rooms",
			Handler: func(c echo.Context) error {
				rooms, err := room.GetRooms(services.App)
				if err != nil {
					return c.JSON(http.StatusBadRequest, "Failed to get rooms")
				}
				return c.JSON(http.StatusOK, rooms)
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	// API Endpoint to get all events for a specific room on a specific day
	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/schedule/day",
			Handler: func(c echo.Context) error {
				roomParam := c.QueryParam("room")
				date := c.QueryParam("date")
				roomSchedule, err := room.GetRoomScheduleForDay(services.App, roomParam, date)
				if err != nil {
					slog.Error("Failed to get room schedule for day: ", "error", err)
					return c.JSON(http.StatusBadRequest, "Failed to get room schedule for day")
				}
				return c.JSON(http.StatusOK, roomSchedule)
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	// API Endpoint to create a new iCal feed
	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/schedule",
			Handler: func(c echo.Context) error {
				roomParam := c.QueryParam("room")
				to := c.QueryParam("to")
				from := c.QueryParam("from")
				roomSchedule, err := room.GetRoomSchedule(services.App, roomParam, from, to)
				if err != nil {
					slog.Error("Failed to get room schedule:", "error", err)
					return c.JSON(http.StatusBadRequest, "Failed to get room schedule")
				}
				return c.JSON(http.StatusOK, roomSchedule)
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	// API Endpoint to get all rooms that have no events in a specific time frame
	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/rooms/free",
			Handler: func(c echo.Context) error {
				from, err := time.ParseTime(c.QueryParam("from"))
				if err != nil {
					slog.Error("Failed to parse time: ", "error", err)
					return c.JSON(http.StatusBadRequest, "Failed to parse time")
				}
				to, err := time.ParseTime(c.QueryParam("to"))
				if err != nil {
					slog.Error("Failed to parse time: ", "error", err)
					return c.JSON(http.StatusBadRequest, "Failed to parse time")
				}
				rooms, err := room.GetFreeRooms(services.App, from, to)
				if err != nil {
					slog.Error("Failed to get free rooms: ", "error", err)
					return c.JSON(http.StatusBadRequest, "Failed to get free rooms")
				}
				return c.JSON(http.StatusOK, rooms)
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	addFeedRoutes(services.App)

	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/course/modules",
			Handler: func(c echo.Context) error {
				modules, err := services.EventService.GetModulesForCourseDistinct(
					c.QueryParam("course"),
					c.QueryParam("semester"),
				)

				if err != nil {
					slog.Error("Failed to get modules for course and semester: ", "error", err)
					return c.JSON(http.StatusBadRequest, "Failed to get modules for course and semester")
				} else {
					return c.JSON(http.StatusOK, modules)
				}
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/modules",
			Handler: func(c echo.Context) error {
				modules, err := services.EventService.GetAllModulesDistinct()
				if err != nil {
					slog.Error("Failed to get modules: ", "error", err)
					return c.JSON(http.StatusBadRequest, "Failed to get modules")
				}
				return c.JSON(http.StatusOK, modules)
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/module",
			Handler: func(c echo.Context) error {
				requestModule := c.QueryParam("uuid")
				module, err := services.EventService.GetModuleByUUID(requestModule)
				if err != nil {
					slog.Error("Failed to get module: ", "error", err)
					return c.JSON(http.StatusBadRequest, "Failed to get module")
				} else {
					return c.JSON(http.StatusOK, module)
				}
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/courses",
			Handler: func(c echo.Context) error {
				semester := c.QueryParam("semester")
				if semester == "" {
					courses := services.CourseService.GetAllCourses()
					return c.JSON(200, courses)
				} else {
					courses := services.CourseService.GetAllCoursesForSemester(semester)
					return c.JSON(200, courses)
				}
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	// api end point to get all courses for a specific semester with courses that have events
	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/courses/events",
			Handler: func(c echo.Context) error {
				semester := c.QueryParam("semester")
				courses, err := services.CourseService.GetAllCoursesForSemesterWithEvents(semester)
				if err != nil {
					slog.Error("Failed to get courses for semester with events: ", "error", err)
					return c.JSON(http.StatusBadRequest, "Failed to get courses for semester with events")
				} else {
					return c.JSON(http.StatusOK, courses)
				}
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	// API Endpoint to get all eventTypes from the database distinct
	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodGet,
			Path:   "/api/events/types",
			Handler: func(c echo.Context) error {
				eventTypes, err := services.EventService.GetEventTypes()
				if err != nil {
					slog.Error("Failed to get event types", "error", err)
					return c.JSON(http.StatusBadRequest, "Failed to get event types")
				} else {
					return c.JSON(http.StatusOK, eventTypes)
				}
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})

	services.App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		_, err := e.Router.AddRoute(echo.Route{
			Method: http.MethodDelete,
			Path:   "/api/events",
			Handler: func(c echo.Context) error {
				err := services.EventService.DeleteAllEventsByCourseAndSemester(
					c.QueryParam("course"),
					c.QueryParam("semester"),
				)
				if err != nil {
					slog.Error("Failed to delete events: ", "error", err)
					return c.JSON(http.StatusBadRequest, "Failed to delete events")
				} else {
					return c.JSON(http.StatusOK, "Events deleted")
				}
			},
			Middlewares: []echo.MiddlewareFunc{
				apis.ActivityLogger(services.App),
				apis.RequireAdminAuth(),
			},
		})
		if err != nil {
			return err
		}
		return nil
	})
}
