// Copyright (C) 2022 Marius Schellenberger

package srv

import (
	"net/http"
	"strings"

	"cachefs/pkg/fs"

	"github.com/go-logr/logr"
)

type PlainServer struct {
	log logr.Logger
	fs  *fs.FS
	h   http.Handler
}

func NewPlainServer(fs *fs.FS, log logr.Logger) http.Handler {
	return &PlainServer{log, fs, http.FileServer(fs)}
}

func skipPlainLog(path string) bool {
	return strings.HasSuffix(path, "favicon.ico")
}

func (ps *PlainServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s := &statusInterceptor{w: w}
	if !skipPlainLog(r.URL.Path) {
		defer func() {
			if s.Status() == http.StatusPartialContent {
				return
			}
			ps.log.Info("access",
				"client", r.RemoteAddr,
				"method", r.Method,
				"status", s.Status(),
				"uri", r.URL.Path,
			)
		}()
	}
	r.Header.Del("If-Modified-Since")
	r.Header.Del("Cache-Control")
	ps.h.ServeHTTP(s, r)
	w.Header().Del("Last-Modified")
}
