package operator

import (
	"context"

	"helmet/pkg/mlbctl"
)

func (oper *Operator) ListForwarders(ctx context.Context, params *mlbctl.ListForwardersParams) (*mlbctl.ListForwardersResult, error) {
	var err error

	res := &mlbctl.ListForwardersResult{
		Forwarders: make([]*mlbctl.Forwarder, 0),
	}
	forws := oper.proxy.ListForwarders(ctx)
	for _, forw := range forws {
		oForw := &mlbctl.Forwarder{
			Type:         forw.Type,
			Lport:        forw.Lport,
			Dport:        forw.Dport,
			Destinations: make([]*mlbctl.Destination, 0),
		}
		for _, dest := range forw.Dests {
			oDest := &mlbctl.Destination{
				Address: dest.Address,
			}
			oForw.Destinations = append(oForw.Destinations, oDest)
		}
		res.Forwarders = append(res.Forwarders, oForw)
	}
	return res, err
}

func (oper *Operator) CreateForwarder(ctx context.Context, params *mlbctl.CreateForwarderParams) (*mlbctl.CreateForwarderResult, error) {
	var err error
	res := &mlbctl.CreateForwarderResult{}
	err = oper.proxy.CreateOrUpdateForwarder(ctx, params.Type, params.Lport, params.Dport, params.Destinations...)
	if err != nil {
		return res, err
	}
	return res, err
}

func (oper *Operator) DeleteForwarder(ctx context.Context, params *mlbctl.DeleteForwarderParams) (*mlbctl.DeleteForwarderResult, error) {
	var err error
	res := &mlbctl.DeleteForwarderResult{}
	err = oper.proxy.DeleteForwarder(ctx, params.Type, params.Lport)
	if err != nil {
		return res, err
	}
	return res, err
}
