package middleware

import (
	"fmt"
	"log/slog"
	"net/http"
	"time"
)

type captureWriter struct {
	http.ResponseWriter
	code int
}

func (c *captureWriter) WriteHeader(statusCode int) {
	c.code = statusCode
	c.ResponseWriter.WriteHeader(statusCode)
}

func Logging(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		cw := &captureWriter{
			ResponseWriter: w,
			code:           200,
		}
		next.ServeHTTP(cw, r)
		slog.Info("request",
			"method", r.Method,
			"path", r.URL.Path,
			"duration", time.Since(start),
			"status", cw.code,
		)
	})
}

// cacheMiddleware adds Cache-Control headers to the response.
func Cache(maxAge time.Duration) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%.0f", maxAge.Seconds()))
			w.Header().Set("Vary", "HX-Request,Accept-Language,Accept-Encoding")
			next.ServeHTTP(w, r)
		})
	}
}
