package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/joho/godotenv"
	"github.com/uptrace/bun/extra/bundebug"

	_ "github.com/lib/pq"

	"fr.latosa-escrima/api"
	"fr.latosa-escrima/core"
	"fr.latosa-escrima/utils"
)

var CORS_AllowOrigin string

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "<html><body><h1>Hello, World!</h1></body></html>")
}

func main() {
	err := godotenv.Load()
	if err != nil {
		log.Fatalf("Error loading .env file: %v", err)
	}
	environ := os.Getenv("ENVIRONMENT")

	port := os.Getenv("BACKEND_DOCKER_PORT")
	hostname := os.Getenv("DATABASE_HOSTNAME")
	postgres_port := os.Getenv("POSTGRES_DOCKER_PORT")
	if environ == "DEV" {
		port = os.Getenv("BACKEND_PORT")
		hostname = "localhost"
		postgres_port = os.Getenv("POSTGRES_PORT")
	}

	dsn := core.DSN{
		Hostname: hostname,
		Port:     postgres_port,
		DBName:   os.Getenv("POSTGRES_DB"),
		User:     os.Getenv("POSTGRES_USER"),
		Password: os.Getenv("POSTGRES_PASSWORD"),
	}
	fmt.Println(dsn.ToString())
	core.DB, err = core.InitDatabase(dsn)
	if err != nil {
		log.Fatal(err)
	}

	core.DB.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true)))

	defer core.DB.Close()

	mux := http.NewServeMux()

	baseRoutes := map[string]core.Handler{
		"/": {
			Handler: handler,
			Middlewares: []core.Middleware{api.Methods("GET"),
				api.HasPermissions("blogs", "insert"),
				api.AuthJWT,
			}},
		"/contact": {
			Handler:     api.HandleContact,
			Middlewares: []core.Middleware{api.Methods("POST"), api.CSRFMiddleware},
		},
		"/csrf-token": {
			Handler:     api.HandleCSRF,
			Middlewares: []core.Middleware{api.Methods("GET"), api.CSRFMiddleware},
		},
	}
	routes := utils.MergeMaps(
		baseRoutes,
		api.UserRoutes,
		api.BlogsRoutes,
		api.EventsRoutes,
		api.MediaRoutes,
		api.PermissionsRoutes,
		api.RolesRoutes,
		api.ShortcodesRoutes,
		api.LocationsRoutes)
	core.HandleRoutes(mux, routes)

	fmt.Printf("Serving on port %s\n", port)
	err = http.ListenAndServe(fmt.Sprintf(":%s", port), api.CORS(mux))
	if err != nil {
		fmt.Printf("Error starting server: %s\n", err)
	}
}
