package networking

import (
	"sync"

	"nadir/internal/rbac"

	"github.com/danielgtaylor/huma/v2"
)

const ModuleID = "networking"

type Module struct {
	// be is the detected network backend (nmcli / networkd / ifupdown). nil when
	// none was found: reads still work (they go through `ip`), writes return 501.
	be backend
	// pending holds the single in-flight change awaiting confirmation, for the
	// timed auto-rollback. See rollback.go.
	pending *pendingChange
	mu      sync.Mutex
}

// New detects the host's network backend once at startup.
func New() *Module { return &Module{be: detect()} }

func (m *Module) ID() string   { return ModuleID }

// Permissions: read to inspect interfaces/routes/DNS; write to reconfigure them
// (apply config, bring links up/down, confirm a pending change).
func (m *Module) Permissions() []rbac.Permission {
	return []rbac.Permission{rbac.Read, rbac.Write}
}

func (m *Module) Register(api huma.API) {
	registerReads(api, m)
	registerWrites(api, m)
	registerHosts(api)
}

func op(permission string) map[string]any {
	return map[string]any{"module": ModuleID, "permission": permission}
}
