package jd

import "fmt"

type EdgeInfo struct {
	Mac  string
	City string
}

func GatewayConfigSet(version int, macaddr string, edges []EdgeInfo) error {
	if version < 0 {
		return fmt.Errorf("版本号不能小于 0")
	}
	if macaddr == "" {
		return fmt.Errorf("macaddr 不能为空")
	}
	if len(edges) > 250 {
		return fmt.Errorf("边缘节点数量不能超过 250")
	}

	rules := make([]GateConfigSetReqRule, len(edges))
	for i, edge := range edges {
		rules[i] = GateConfigSetReqRule{
			Enable:   true,
			Edge:     []string{edge.Mac},
			Network:  []string{fmt.Sprintf("172.30.168.%d", i+2)},
			Cityhash: edge.City, // 每个 edge 的城市应当相同
		}
	}

	req := GatewayConfigSetReq{
		Macaddr: macaddr,
		Config: GateConfigSetReqConfig{
			Id:    version,
			Rules: rules,
		},
	}

	if _, err := Post("/gateway/config/set", req); err != nil {
		return fmt.Errorf("设置网关配置失败: %v", err)
	}

	return nil
}

type GatewayConfigSetReq struct {
	Macaddr string                 `json:"macaddr"`
	Config  GateConfigSetReqConfig `json:"config"`
}

type GateConfigSetReqConfig struct {
	Id    int                    `json:"id"`
	Rules []GateConfigSetReqRule `json:"rules"`
}

type GateConfigSetReqRule struct {
	Enable   bool     `json:"enable"`
	Edge     []string `json:"edge"`
	Network  []string `json:"network"`
	Cityhash string   `json:"cityhash"`
}
