package main

import (
	"encoding/json"
	"log"
	"net/http"

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

func main() {
	if err := initDB(); err != nil {
		log.Fatalf("db init: %v", err)
	}
	defer db.Close()

	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)

	// --- Auth (öffentlich) ---
	r.Post("/auth/login", handleLogin)
	r.Get("/auth/logout", handleLogout)
	r.Post("/auth/newuser", handleNewUser)
	r.Get("/auth/sessioninfo", handleSessionInfo)
	r.Get("/auth/headerbar", handleHeaderbar)

	// --- Entries ---
	r.Get("/entry/feed/{page}", handleFeed)
	r.Get("/entry/{pid}/interactions/{mode}", handleInteractions)

	// --- User (öffentlich) ---
	r.Get("/u/{username}", handleUserPage)
	r.Get("/user/delete", handleUserDelete)

	// --- Geschützt (Session erforderlich) ---
	r.Group(func(r chi.Router) {
		r.Use(requireAuth)
		r.Post("/entry/create", handleCreateEntry)
		r.Get("/user/info", handleUserInfo)
	})

	// Hochgeladene Medien + alte statische Assets
	r.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

	// Neues JS-Frontend
	r.Handle("/*", http.FileServer(http.Dir("web")))

	const addr = ":8080"
	log.Printf("kver listening on %s", addr)
	log.Fatal(http.ListenAndServe(addr, r))
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

func writeError(w http.ResponseWriter, status int, msg string) {
	writeJSON(w, status, map[string]string{"error": msg})
}
