package main

import (
	"context"
	"encoding/gob"
	"log"
	"os"

	"ordr-api/auth"
	"ordr-api/auth/middleware"
	"ordr-api/controllers"
	"ordr-api/corsmiddleware"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/joho/godotenv"
)

func init_db_pool(databaseUrl string) (*pgxpool.Pool, error) {
	config, err := pgxpool.ParseConfig(databaseUrl)
	if err != nil {
		log.Fatalf("Failed to load pgx pool config %s....", err)
	}

	pool, err := pgxpool.NewWithConfig(context.Background(), config)

	err = pool.Ping(context.Background())
	if err != nil {
		log.Fatalf("Unable to ping database: %v\n", err)
	}

	return pool, err
}

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

	// Configure CORS middleware
	r.NoRoute(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", os.Getenv("ALLOWED_ORIGIN"))
		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")

		log.Printf("%s", c.Request.Method)
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.AbortWithStatus(404)
	})

	if err := godotenv.Load(); err != nil {
		log.Fatalf("Failed to load the env vars: %v", err)
	}

	authenticator, auth_err := auth.New()
	if auth_err != nil {
		log.Fatal("ERROR: Failed to initialize Authenticator")
		return
	}

	pool, pool_err := init_db_pool(os.Getenv("CONNECTION_STRING"))

	if pool_err != nil {
		log.Fatal("ERROR: Failed to initialize DB pooL")
	}

	router := gin.Default()

	router.SetTrustedProxies([]string{"127.0.0.1/32", "::1/128"})

	store := cookie.NewStore([]byte(os.Getenv("COOKIE_SECRET")))
	router.Use(sessions.Sessions("auth-session", store))

	// Middleware Function Declarations
	user_authenticated := middleware.IsAuthenticated(authenticator)
	user_in_db := middleware.UserInDatabase(pool)
	user_active := middleware.UserIsActive(pool)
	user_is_admin := middleware.IsAdmin(pool)

	gob.Register(map[string]interface{}{})
	router.GET("/", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, controllers.BaseFunction)
	router.GET("/auth/login", corsmiddleware.CORSMiddleware, auth.LoginHandler(authenticator))
	router.GET("/auth/logout", corsmiddleware.CORSMiddleware, auth.LogoutHandler)
	router.GET("/auth/logout_callback", corsmiddleware.CORSMiddleware, auth.LogoutCallbackHandler(store))
	router.GET("/callback", corsmiddleware.CORSMiddleware, auth.AuthenticationCallbackHandler(authenticator))
	router.OPTIONS("./users", corsmiddleware.CORSMiddleware)
	router.PUT("/users", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.GetUserTable(pool))
	router.GET("/user/current", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetCurrentAuthenticatedUser(pool))
	router.GET("/item/price/current", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetCurrentItemPrice(pool))
	router.GET("/order/items", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetOrderItems(pool))
	router.GET("/order", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetOrderByOrderId(pool))
	router.PUT("/order/table", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetOrderTable(pool))
	router.OPTIONS("/order/table", corsmiddleware.CORSMiddleware)
	router.GET("/items", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, controllers.GetItems(pool))
	router.OPTIONS("/item/history", corsmiddleware.CORSMiddleware)
	router.GET("/item/history", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.GetItemHistory(pool))
	router.POST("/position/create", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.CreatePosition(pool))
	router.POST("/item/create", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.CreateItem(pool))
	router.OPTIONS("/item/create", corsmiddleware.CORSMiddleware)
	router.POST("/order/create", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.CreateOrder(pool))
	router.OPTIONS("/order/create", corsmiddleware.CORSMiddleware)

	router.PUT("/user/name", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.SetUserName(pool))
	router.PUT("/user/promote", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.PromoteUser(pool))
	router.PUT("/user/demote", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.DemoteUser(pool))
	router.OPTIONS("/user/promote", corsmiddleware.CORSMiddleware)
	router.OPTIONS("/user/demote", corsmiddleware.CORSMiddleware)

	router.PUT("/user/position", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.SetUserPosition(pool))
	router.PUT("/item/price", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.SetItemPrice(pool))
	router.OPTIONS("/item/price", corsmiddleware.CORSMiddleware)
	router.PUT("/order/item", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.AddItemToOrder(pool))
	router.OPTIONS("/order/item", corsmiddleware.CORSMiddleware)
	router.PUT("/item/made", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.SetItemMade(pool))
	router.OPTIONS("/item/made", corsmiddleware.CORSMiddleware)
	router.PUT("/item/quantity", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.SetItemQuantity(pool))
	router.OPTIONS("/item/quantity", corsmiddleware.CORSMiddleware)
	router.PUT("/user/activate", corsmiddleware.CORSMiddleware, middleware.IsAuthenticated(authenticator), middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.ActivateUser(pool))
	router.OPTIONS("/user/activate", corsmiddleware.CORSMiddleware)

	router.DELETE("/user/deactivate", corsmiddleware.CORSMiddleware, middleware.IsAuthenticated(authenticator), middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.DeactivateUser(pool))
	router.OPTIONS("/user/deactivate", corsmiddleware.CORSMiddleware)

	router.DELETE("/order/item", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.DeleteOrderItem(pool))
	router.DELETE("/order", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, controllers.DeleteOrder(pool))
	router.DELETE("/item", corsmiddleware.CORSMiddleware, user_authenticated, middleware.GetUserProfile, user_in_db, user_active, user_is_admin, controllers.DeleteItem(pool))

	router.Run("localhost:8080")
}
