package middleware

import (
	"net/http"
	"time"

	"github.com/go-chi/chi/v5/middleware"
	"go.uber.org/zap"
)

// Logger middleware adds request logging
func Logger(logger *zap.Logger) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()

			// Create a wrapped response writer to capture the status code
			ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)

			// Process request
			next.ServeHTTP(ww, r)

			// Calculate request time
			latency := time.Since(start)

			// Log request details
			logger.Info("API Request",
				zap.String("method", r.Method),
				zap.String("path", r.URL.Path),
				zap.String("query", r.URL.RawQuery),
				zap.Int("status", ww.Status()),
				zap.Duration("latency", latency),
				zap.String("ip", r.RemoteAddr),
				zap.String("user-agent", r.UserAgent()),
				zap.Int("bytes", ww.BytesWritten()),
			)
		})
	}
}

// AuditLog middleware records detailed information about DICOM requests
func AuditLog(logger *zap.Logger) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Extract user info (placeholder for now)
			userID := "TODO: userID"

			// Process request
			ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
			next.ServeHTTP(ww, r)

			// Audit log after request completes
			logger.Info("DICOM Access",
				zap.String("userID", userID),
				zap.String("action", r.Method),
				zap.String("resource", r.URL.Path),
				zap.Int("status", ww.Status()),
			)
		})
	}
}
