/*
 * SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
 * SPDX-License-Identifier: AGPL-3.0-only
 */

package http

import (
	"log"
	"net/http"
	"os"
	"time"
)

type loggerResponseWriter struct {
	http.ResponseWriter
	statusCode   int
	responseSize int
}

func (w *loggerResponseWriter) WriteHeader(statusCode int) {
	w.statusCode = statusCode
	w.ResponseWriter.WriteHeader(statusCode)
}

func (w *loggerResponseWriter) Write(b []byte) (int, error) {
	w.responseSize += len(b)
	return w.ResponseWriter.Write(b)
}

func (w *loggerResponseWriter) Flush() {
	if f, ok := w.ResponseWriter.(http.Flusher); ok {
		f.Flush()
	}
}

func LogRequest(next http.Handler) http.Handler {
	stdout := log.New(os.Stdout, "", log.LstdFlags)
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		t := time.Now()
		logger := loggerResponseWriter{w, 0, 0}

		requestPath := r.URL.Path
		next.ServeHTTP(&logger, r)

		statusCode := logger.statusCode
		if statusCode == 0 {
			statusCode = http.StatusOK
		}
		stdout.Printf("HTTP - %s %s \"%s\" %d %d %s\n",
			RemoteAddr(r),
			r.Method,
			requestPath,
			statusCode,
			logger.responseSize,
			time.Since(t),
		)
	})
}
