package auth

import (
	"net/http"
	"path"
	"strings"

	"github.com/wormhole/wormhole/internal/store"
)

func shouldLogVisitorAccess(reqPath string) bool {
	if reqPath == visitorLoginPath {
		return false
	}
	base := strings.Split(reqPath, "?")[0]
	ext := strings.ToLower(path.Ext(base))
	switch ext {
	case ".js", ".css", ".ico", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg",
		".woff", ".woff2", ".ttf", ".eot", ".map", ".wasm":
		return false
	}
	return true
}

func (ra *ResourceAuth) logVisitorAccess(userID uint, resourceType string, resourceID uint, action string, r *http.Request) {
	if ra.store == nil {
		return
	}
	reqPath := r.URL.RequestURI()
	if action == "access" && !shouldLogVisitorAccess(r.URL.Path) {
		return
	}
	if len(reqPath) > 512 {
		reqPath = reqPath[:512]
	}
	ua := r.UserAgent()
	if len(ua) > 256 {
		ua = ua[:256]
	}
	entry := &store.VisitorAccessLog{
		UserID:       userID,
		ResourceType: resourceType,
		ResourceID:   resourceID,
		Action:       action,
		Method:       r.Method,
		Path:         reqPath,
		IP:           ExtractRemoteIP(r),
		UserAgent:    ua,
	}
	go func() {
		_ = ra.store.AppendVisitorAccessLog(entry)
	}()
}
