package main

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

	"com.sismedika.com.absensi/graph/generated"
	"com.sismedika.com.absensi/graph/resolver"
	"com.sismedika.com.absensi/pkg/auth"
	"com.sismedika.com.absensi/pkg/config"
	"com.sismedika.com.absensi/pkg/database"
	"github.com/99designs/gqlgen/graphql/handler"
	"github.com/99designs/gqlgen/graphql/playground"
	"github.com/go-chi/chi"
	"github.com/rs/cors"
)

const defaultPort = "8080"

func main() {
	config.Load()
	port := os.Getenv("PORT")
	if port == "" {
		port = defaultPort
	}
	router := chi.NewRouter()
	// database
	database.InitDB()
	defer database.Handle.Close()

	router.Use(
		auth.Middleware(),
		// dataloader.Middleware,
		cors.New(cors.Options{
			AllowedOrigins:   []string{"*"},
			AllowedHeaders:   []string{"*"},
			AllowCredentials: true,
			Debug:            false,
		}).Handler)

	srv := handler.NewDefaultServer(
		generated.NewExecutableSchema(generated.Config{Resolvers: &resolver.Resolver{}}))

	router.Handle("/", playground.Handler("GraphQL playground", "/query"))
	router.Handle("/query", srv)
	log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
	log.Fatal(http.ListenAndServe(":"+port, router))
}
