package daemon

import (
	"context"
	"testing"

	"banger/internal/model"
	"banger/internal/vmdns"
)

func TestSyncVMDNSResolverRoutingConfiguresResolved(t *testing.T) {
	runner := &scriptedRunner{
		t: t,
		steps: []runnerStep{
			{call: runnerCall{name: "ip", args: []string{"link", "show", model.DefaultBridgeName}}, out: []byte("1: br-fc\n")},
			sudoStep("", nil, "resolvectl", "dns", model.DefaultBridgeName, "127.0.0.1:42069"),
			sudoStep("", nil, "resolvectl", "domain", model.DefaultBridgeName, vmResolverRouteDomain),
			sudoStep("", nil, "resolvectl", "default-route", model.DefaultBridgeName, "no"),
		},
	}
	cfg := model.DaemonConfig{BridgeName: model.DefaultBridgeName}
	n := &HostNetwork{
		runner: runner, config: cfg, vmDNS: new(vmdns.Server),
		lookupExecutable: func(name string) (string, error) {
			if name == "resolvectl" {
				return "/usr/bin/resolvectl", nil
			}
			return "", nil
		},
		vmDNSAddr: func(*vmdns.Server) string { return "127.0.0.1:42069" },
	}

	if err := n.syncVMDNSResolverRouting(context.Background()); err != nil {
		t.Fatalf("syncVMDNSResolverRouting: %v", err)
	}
	runner.assertExhausted()
}

func TestClearVMDNSResolverRoutingRevertsBridgeConfig(t *testing.T) {
	runner := &scriptedRunner{
		t: t,
		steps: []runnerStep{
			{call: runnerCall{name: "ip", args: []string{"link", "show", model.DefaultBridgeName}}, out: []byte("1: br-fc\n")},
			sudoStep("", nil, "resolvectl", "revert", model.DefaultBridgeName),
		},
	}
	cfg := model.DaemonConfig{BridgeName: model.DefaultBridgeName}
	n := &HostNetwork{
		runner: runner, config: cfg,
		lookupExecutable: func(name string) (string, error) {
			if name == "resolvectl" {
				return "/usr/bin/resolvectl", nil
			}
			return "", nil
		},
	}

	if err := n.clearVMDNSResolverRouting(context.Background()); err != nil {
		t.Fatalf("clearVMDNSResolverRouting: %v", err)
	}
	runner.assertExhausted()
}
