package http

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

	"mind/internal/config"
	"mind/internal/glue"
	"mind/internal/logx"
)

type server struct {
	log  *logx.Logger
	cfg  config.Config
	glue *glue.Glue
}

func NewRouter(l *logx.Logger, c config.Config, g *glue.Glue) http.Handler {
	s := &server{log: l, cfg: c, glue: g}
	mux := http.NewServeMux()
	mux.HandleFunc("/healthz", s.health)
	mux.HandleFunc("/conversations", s.conversations)
	mux.HandleFunc("/branches", s.branches)
	mux.HandleFunc("/completion", s.completion)
	mux.HandleFunc("/linearize", s.linearize)
	return withCommon(mux)
}

func (s *server) health(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(200)
	_, _ = w.Write([]byte("ok"))
}

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