package daemon

import (
	"context"
	"strings"
)

const vmResolverRouteDomain = "~vm"

func (n *HostNetwork) syncVMDNSResolverRouting(ctx context.Context) error {
	if n == nil || n.vmDNS == nil {
		return nil
	}
	if strings.TrimSpace(n.config.BridgeName) == "" {
		return nil
	}
	if _, err := n.lookupExecutable("resolvectl"); err != nil {
		return nil
	}
	if _, err := n.runner.Run(ctx, "ip", "link", "show", n.config.BridgeName); err != nil {
		return nil
	}
	serverAddr := strings.TrimSpace(n.vmDNSAddr(n.vmDNS))
	if serverAddr == "" {
		return nil
	}
	return n.privOps().SyncResolverRouting(ctx, serverAddr)
}

func (n *HostNetwork) clearVMDNSResolverRouting(ctx context.Context) error {
	if n == nil || strings.TrimSpace(n.config.BridgeName) == "" {
		return nil
	}
	if _, err := n.lookupExecutable("resolvectl"); err != nil {
		return nil
	}
	if _, err := n.runner.Run(ctx, "ip", "link", "show", n.config.BridgeName); err != nil {
		return nil
	}
	return n.privOps().ClearResolverRouting(ctx)
}

func (n *HostNetwork) ensureVMDNSResolverRouting(ctx context.Context) {
	if err := n.syncVMDNSResolverRouting(ctx); err != nil && n.logger != nil {
		n.logger.Warn("vm dns resolver route sync failed", "bridge", n.config.BridgeName, "error", err.Error())
	}
}
