package api

import (
	"agent/defines/devent/daction"
	"agent/defines/devent/dcategory"
	"agent/defines/devent/dkind"
	"context"
	"encoding/json"
)

func AgentTunnelPortGet(ctx context.Context, client IClient,
	portUuid UUID,
) (res PortParams, err error) {
	event := agentTunnelPortGetEvent(portUuid)
	data, err := ExecuteAndGetData(ctx, client, event)
	if err != nil {
		return res, err
	}
	return res, json.Unmarshal(data, &res)
}

func agentTunnelPortGetEvent(portUuid UUID) IEvent {
	meta := map[string]any{
		"port_uuid": portUuid,
	}

	minTrashSize := int64(32)
	maxTrashSize := int64(128)

	return NewEvent(
		dkind.AgentToService,
		[]Category{dcategory.Agent, dcategory.Tunnel, dcategory.Port},
		daction.Get,
		meta,

		NewEventOpts{
			Request: &EventRequestOpts{
				MinTrashSize: &minTrashSize,
				MaxTrashSize: &maxTrashSize,
			},
			Response: &EventResponseOpts{
				MinTrashSize: &minTrashSize,
				MaxTrashSize: &maxTrashSize,
			},
		},
	)
}

func AgentTunnelPortUpdate(ctx context.Context, client IClient,
	portUuid UUID,
	status int,
	tunErr ...error,
) (err error) {
	var errMsg string
	if len(tunErr) > 0 && tunErr[0] != nil {
		errMsg = tunErr[0].Error()
	}
	event := agentTunnelPortUpdateEvent(portUuid, status, errMsg)
	_, err = ExecuteAndGetData(ctx, client, event)
	return err
}

func agentTunnelPortUpdateEvent(portUuid UUID, status int, errMsg string) IEvent {
	meta := map[string]any{
		"port_uuid": portUuid,
		"status":    status,
		"error":     errMsg,
	}

	minTrashSize := int64(32)
	maxTrashSize := int64(128)

	return NewEvent(
		dkind.AgentToService,
		[]Category{dcategory.Agent, dcategory.Tunnel, dcategory.Port},
		daction.Update,
		meta,

		NewEventOpts{
			Request: &EventRequestOpts{
				MinTrashSize: &minTrashSize,
				MaxTrashSize: &maxTrashSize,
			},
			Response: &EventResponseOpts{
				MinTrashSize: &minTrashSize,
				MaxTrashSize: &maxTrashSize,
			},
		},
	)
}
