// Package handler provides the HTTP handler for the marka server
package handler

import (
	"errors"
	"net/http"

	"git.max-richter.dev/max/marka/server/internal/adapters"
)

type Handler struct {
	adapter adapters.FileAdapter
}

func (h *Handler) get(w http.ResponseWriter, target string) {
	entry, err := h.adapter.Read(target)
	if err != nil {
		if errors.Is(err, adapters.ErrNotFound) {
			writeError(w, http.StatusNotFound, err)
			return
		}
		writeError(w, http.StatusInternalServerError, err)
		return
	}

	if entry.Type == "file" {
		// For non-markdown files, content is []byte, write it directly
		if contentBytes, ok := entry.Content.([]byte); ok {
			w.Header().Set("Content-Type", entry.MIME)
			w.Write(contentBytes)
			return
		}
		// For markdown files, content is parsed, return the whole Entry as JSON
		writeJSON(w, http.StatusOK, entry)
		return
	}

	// For directories, return the whole Entry as JSON
	if entry.Type == "dir" {
		writeJSON(w, http.StatusOK, entry)
		return
	}

	writeError(w, http.StatusInternalServerError, errors.New("unknown entry type"))
}

func (h *Handler) post(w http.ResponseWriter, target string) {
}

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	reqPath := r.URL.Path
	if reqPath == "" {
		reqPath = "/"
	}

	target := cleanURLLike(reqPath)

	switch r.Method {
	case http.MethodGet:
		h.get(w, target)
	case http.MethodPost:
		h.post(w, target)
	default:
		writeError(w, http.StatusMethodNotAllowed, errors.New("method not allowed"))
	}
}

func NewHandler(adapter adapters.FileAdapter) http.Handler {
	return &Handler{
		adapter: adapter,
	}
}
