package main

import (
	"net/http"

	"gitea.tbdevent.eu/TBD/reforger_crawler_main/controllers"
	"gitea.tbdevent.eu/TBD/reforger_crawler_main/initializers"

	"github.com/gin-gonic/gin"
)

func init() {
	initializers.Load()
	initializers.ConnectToDB()
}

func main() {
	r := gin.Default()
	r.Use(CORSMiddleware())

	back := r.Group("/back")
	{
		back.GET("/addon", controllers.CheckAllowed, controllers.GetCurrentState)
		back.POST("/addon", controllers.CheckAllowed, controllers.CreateAddon)
		back.GET("/nextToBeIndexed", controllers.CheckAllowed, controllers.GetNextToBeIndexed)
		back.POST("/submitAddon", controllers.CheckAllowed, controllers.SaveIndexingResult)
	}

	admin := r.Group("/admin")
	{
		admin.GET("/duplicates", controllers.CheckAdmin)
		admin.POST("/setPriority", controllers.CheckAdmin)
		admin.POST("/setToBeIndexed", controllers.CheckAdmin)
	}

	r.Run(initializers.IP + ":" + initializers.PORT)
}

func CORSMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
		orig := c.Request.Header.Clone().Get("Origin")
        c.Writer.Header().Set("Access-Control-Allow-Origin", orig)
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(http.StatusNoContent)
            return
        }

        c.Next()
    }
}

func OptionsMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
		if c.Request.Method != "OPTIONS" {
			c.Next()
		} else {
			c.AbortWithStatus(http.StatusOK)
		}
    }
}
