package main

import (
	"context"
	"io/fs"
	"net/http"
	"os"

	"xtablo-backend/internal/db"
	"xtablo-backend/internal/web/handlers"

	chi "github.com/go-chi/chi/v5"
)

func newRouter() http.Handler {
	databaseURL := os.Getenv("DATABASE_URL")
	repo, err := db.NewPostgresAuthRepository(context.Background(), databaseURL)
	if err != nil {
		panic(err)
	}
	return newRouterWithHandler(handlers.NewAuthHandler(repo))
}

func newTestRouter() http.Handler {
	return newRouterWithHandler(handlers.NewAuthHandler(handlers.NewInMemoryAuthRepository()))
}

func newRouterWithHandler(authHandler *handlers.AuthHandler) http.Handler {
	mux := chi.NewRouter()
	staticFS := os.DirFS("static")

	// Views
	mux.Get("/", authHandler.GetHome())
	mux.Get("/tasks", authHandler.GetTasksPage())
	mux.Post("/tasks", authHandler.PostTasks())
	mux.Get("/tasks/{taskID}/edit", authHandler.GetEditTaskModal())
	mux.Patch("/tasks/{taskID}", authHandler.PatchTask())
	mux.Delete("/tasks/{taskID}", authHandler.DeleteTask())
	mux.Get("/tablos", authHandler.GetTablosPage())
	mux.Get("/planning", authHandler.GetPlanningPage())
	mux.Get("/chat", authHandler.GetChatPage())
	mux.Get("/files", authHandler.GetFilesPage())
	mux.Get("/feedback", authHandler.GetFeedbackPage())
	mux.Post("/tablos", authHandler.PostTablos())
	mux.Get("/tablos/{tabloID}/edit", authHandler.GetEditTabloModal())
	mux.Post("/tablos/{tabloID}", authHandler.PostTabloUpdate())
	mux.Delete("/tablos/{tabloID}", authHandler.DeleteTablo())
	mux.Get("/login", authHandler.GetLoginPage())
	mux.Get("/signup", authHandler.GetSignupPage())
	mux.Post("/login", authHandler.PostLogin())
	mux.Post("/signup", authHandler.PostSignup())
	mux.Post("/logout", authHandler.PostLogout())

	mux.Handle("/static/*", http.StripPrefix("/static/", http.FileServerFS(os.DirFS("static"))))
	mux.Handle("/pwa-icons/*", http.StripPrefix("/pwa-icons/", http.FileServerFS(os.DirFS("static/pwa-icons"))))
	mux.HandleFunc("/logo_dark.png", serveStaticFile(staticFS, "logo_dark.png", "image/png"))
	mux.HandleFunc("/logo_white.png", serveStaticFile(staticFS, "logo_white.png", "image/png"))
	mux.HandleFunc("/manifest.webmanifest", serveStaticFile(staticFS, "manifest.webmanifest", "application/manifest+json"))
	mux.NotFound(authHandler.GetNotFound())

	return mux
}

func serveStaticFile(fileSystem fs.FS, path string, contentType string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if contentType != "" {
			w.Header().Set("Content-Type", contentType)
		}
		http.ServeFileFS(w, r, fileSystem, path)
	}
}
