package gateway

import (
	"context"

	"github.com/tech/sendico/pkg/api/routers/gsresponse"
	gatewayv1 "github.com/tech/sendico/pkg/proto/common/gateway/v1"
	mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
	"google.golang.org/protobuf/proto"
)

// ListGatewayInstances exposes the Monetix gateway instance descriptors.
func (s *Service) ListGatewayInstances(ctx context.Context, req *mntxv1.ListGatewayInstancesRequest) (*mntxv1.ListGatewayInstancesResponse, error) {
	return executeUnary(ctx, s, "ListGatewayInstances", s.handleListGatewayInstances, req)
}

func (s *Service) handleListGatewayInstances(_ context.Context, _ *mntxv1.ListGatewayInstancesRequest) gsresponse.Responder[mntxv1.ListGatewayInstancesResponse] {
	items := make([]*gatewayv1.GatewayInstanceDescriptor, 0, 1)
	if s.gatewayDescriptor != nil {
		items = append(items, cloneGatewayDescriptor(s.gatewayDescriptor))
	}
	return gsresponse.Success(&mntxv1.ListGatewayInstancesResponse{Items: items})
}

func cloneGatewayDescriptor(src *gatewayv1.GatewayInstanceDescriptor) *gatewayv1.GatewayInstanceDescriptor {
	if src == nil {
		return nil
	}
	cp := proto.Clone(src).(*gatewayv1.GatewayInstanceDescriptor)
	if src.Currencies != nil {
		cp.Currencies = append([]string(nil), src.Currencies...)
	}
	if src.Capabilities != nil {
		cp.Capabilities = proto.Clone(src.Capabilities).(*gatewayv1.RailCapabilities)
	}
	if src.Limits != nil {
		limits := &gatewayv1.Limits{}
		if src.Limits.VolumeLimit != nil {
			limits.VolumeLimit = map[string]string{}
			for key, value := range src.Limits.VolumeLimit {
				limits.VolumeLimit[key] = value
			}
		}
		if src.Limits.VelocityLimit != nil {
			limits.VelocityLimit = map[string]int32{}
			for key, value := range src.Limits.VelocityLimit {
				limits.VelocityLimit[key] = value
			}
		}
		if src.Limits.CurrencyLimits != nil {
			limits.CurrencyLimits = map[string]*gatewayv1.LimitsOverride{}
			for key, value := range src.Limits.CurrencyLimits {
				if value == nil {
					continue
				}
				limits.CurrencyLimits[key] = proto.Clone(value).(*gatewayv1.LimitsOverride)
			}
		}
		cp.Limits = limits
	}
	return cp
}
