package upstream //https://github.com/docker/cli/blob/master/cli/command/service/scale.go

import (
	"context"
	"fmt"

	"coopcloud.tech/abra/pkg/log"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
)

// RunServiceScale scales a service (useful for restart action)
func RunServiceScale(ctx context.Context, cl *client.Client, serviceID string, scale uint64) error {
	service, _, err := cl.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{})
	if err != nil {
		return err
	}

	serviceMode := &service.Spec.Mode
	if serviceMode.Replicated != nil {
		serviceMode.Replicated.Replicas = &scale
	} else if serviceMode.ReplicatedJob != nil {
		serviceMode.ReplicatedJob.TotalCompletions = &scale
	} else {
		return fmt.Errorf("scale can only be used with replicated or replicated-job mode")
	}

	response, err := cl.ServiceUpdate(
		ctx,
		service.ID,
		service.Version,
		service.Spec,
		types.ServiceUpdateOptions{},
	)
	if err != nil {
		return err
	}

	for _, warning := range response.Warnings {
		log.Warn(warning)
	}

	return nil
}
