package middleware

import (
	"net/http"
	"strings"

	httperrors "github.com/explorer/backend/libs/go-http-errors"
)

// SecurityMiddleware adds security headers
type SecurityMiddleware struct{}

// NewSecurityMiddleware creates a new security middleware
func NewSecurityMiddleware() *SecurityMiddleware {
	return &SecurityMiddleware{}
}

// AddSecurityHeaders adds security headers to responses
func (m *SecurityMiddleware) AddSecurityHeaders(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Content Security Policy
		// unsafe-eval required by ethers.js v5 UMD from CDN (ABI decoding)
		w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://unpkg.com https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; font-src 'self' https://cdnjs.cloudflare.com; img-src 'self' data: https:; connect-src 'self' https://blockscout.defi-oracle.io https://explorer.d-bis.org https://rpc-http-pub.d-bis.org wss://rpc-ws-pub.d-bis.org http://192.168.11.221:8545 ws://192.168.11.221:8546;")

		// X-Frame-Options (click-jacking protection)
		w.Header().Set("X-Frame-Options", "DENY")

		// X-Content-Type-Options
		w.Header().Set("X-Content-Type-Options", "nosniff")

		// X-XSS-Protection
		w.Header().Set("X-XSS-Protection", "1; mode=block")

		// Strict-Transport-Security
		w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")

		// Referrer-Policy
		w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")

		// Permissions-Policy
		w.Header().Set("Permissions-Policy", "geolocation=(), microphone=(), camera=()")

		next.ServeHTTP(w, r)
	})
}

// BlockWriteCalls blocks contract write calls except WETH operations
func (m *SecurityMiddleware) BlockWriteCalls(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Only apply to POST requests (write operations)
		if r.Method == http.MethodPost {
			// Check if this is a WETH operation (allowed)
			path := r.URL.Path
			if !strings.Contains(path, "weth") && !strings.Contains(path, "wrap") && !strings.Contains(path, "unwrap") {
				// Block other write operations for Track 1
				if strings.HasPrefix(path, "/api/v1/track1") {
					httperrors.WriteJSON(w, http.StatusForbidden, "FORBIDDEN", "Write operations not allowed for Track 1 (public)")
					return
				}
			}
		}

		next.ServeHTTP(w, r)
	})
}
