package middlewares

import (
	"bssapp-backend/auth"
	"net/http"
	"time"

	"bssapp-backend/internal/auditlog"
)

type ResponseWriter struct {
	http.ResponseWriter
	status int
}

func NewResponseWriter(w http.ResponseWriter) *ResponseWriter {
	return &ResponseWriter{
		ResponseWriter: w,
		status:         http.StatusOK,
	}
}

func (rw *ResponseWriter) WriteHeader(code int) {
	rw.status = code
	rw.ResponseWriter.WriteHeader(code)
}

func (rw *ResponseWriter) Status() int { return rw.status }

func Audit(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		start := time.Now()
		rw := NewResponseWriter(w)

		next.ServeHTTP(rw, r)

		// ✅ AuthMiddleware sonrası burada claims VAR
		var dfusrID int64
		var username, roleCode string

		if claims, ok := auth.GetClaimsFromContext(r.Context()); ok && claims != nil {
			dfusrID = int64(claims.ID)
			username = claims.Username
			roleCode = claims.RoleCode // token’da varsa
		}

		entry := auditlog.ActivityLog{
			DfUsrID:  dfusrID,
			Username: username,
			RoleCode: roleCode,

			ActionType:     "route_access",
			ActionCategory: "nav",
			ActionTarget:   r.URL.Path,
			Description:    r.Method + " " + r.URL.Path,

			IpAddress: r.RemoteAddr,
			UserAgent: r.UserAgent(),
			SessionID: "",

			RequestStartedAt:  start,
			RequestFinishedAt: time.Now(),
			DurationMs:        int(time.Since(start).Milliseconds()),
			HttpStatus:        rw.Status(),
			IsSuccess:         rw.Status() < 400,
		}

		auditlog.Write(entry)
	})
}
