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{}}))

	// get file selfie
	router.Get("/img/{typeAbsensi}/{subfolder}/{imgname}", func(w http.ResponseWriter, r *http.Request) {

		// inisialisasi
		var urlPath string

		// get from url param
		typeAbsensi := chi.URLParam(r, "typeAbsensi")
		subfolder := chi.URLParam(r, "subfolder")
		imgname := chi.URLParam(r, "imgname")

		// check param empty
		if typeAbsensi == "" {
			w.Write([]byte("Invalid typeAbsensi"))
			return
		}

		if subfolder == "" {
			w.Write([]byte("Invalid subfolder"))
			return
		}

		if imgname == "" {
			// w.Write([]byte("Invalid imgname"))
			http.ServeFile(w, r, config.Data.Get("notFoundImage"))
			// return
		}

		// klu clockin
		if typeAbsensi == "clockin" {
			// urlPath = "./selfie_attachment/" + subfolder + "/" + imgname
			urlPath = config.Data.Get("clockInFolder") + subfolder + "/" + imgname
		}

		if typeAbsensi == "clockout" {
			// urlPath = "./selfie_attachment/" + subfolder + "/" + imgname
			urlPath = config.Data.Get("clockOutFolder") + subfolder + "/" + imgname
		}

		if typeAbsensi == "cuti" {
			// urlPath = "./cuti/" + subfolder + "/" + imgname
			urlPath = config.Data.Get("cutiFolder") + subfolder + "/" + imgname
		}

		if typeAbsensi == "ijin" {
			// urlPath = "./ijin/" + subfolder + "/" + imgname
			urlPath = config.Data.Get("ijinFolder") + subfolder + "/" + imgname
		}

		_, err := os.ReadFile(urlPath)

		// gambar tidak ditemukan akan return image not found
		if err != nil {
			// w.Write([]byte("Invalid Attachment Clock In"))
			// return
			http.ServeFile(w, r, config.Data.Get("notFoundImage"))
			return
		}

		http.ServeFile(w, r, urlPath)
	})

	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))
}
