package internal

import (
	"context"
	"fmt"
	"io"

	"coopcloud.tech/abra/pkg/config"
	containerPkg "coopcloud.tech/abra/pkg/container"
	"coopcloud.tech/abra/pkg/log"
	"coopcloud.tech/abra/pkg/service"
	"coopcloud.tech/abra/pkg/upstream/container"
	"github.com/docker/cli/cli/command"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	dockerClient "github.com/docker/docker/client"
)

// RetrieveBackupBotContainer gets the deployed backupbot container.
func RetrieveBackupBotContainer(cl *dockerClient.Client) (types.Container, error) {
	ctx := context.Background()
	chosenService, err := service.GetServiceByLabel(ctx, cl, config.BackupbotLabel, NoInput)
	if err != nil {
		return types.Container{}, fmt.Errorf("no backupbot discovered, is it deployed?")
	}

	log.Debugf("retrieved %s as backup enabled service", chosenService.Spec.Name)

	filters := filters.NewArgs()
	filters.Add("name", chosenService.Spec.Name)
	targetContainer, err := containerPkg.GetContainer(
		ctx,
		cl,
		filters,
		NoInput,
	)
	if err != nil {
		return types.Container{}, err
	}

	return targetContainer, nil
}

// RunBackupCmdRemote runs a backup related command on a remote backupbot container.
func RunBackupCmdRemote(
	cl *dockerClient.Client,
	backupCmd string,
	containerID string,
	execEnv []string) (io.Writer, error) {
	execBackupListOpts := types.ExecConfig{
		AttachStderr: true,
		AttachStdin:  true,
		AttachStdout: true,
		Cmd:          []string{"/usr/bin/backup", "--", backupCmd},
		Detach:       false,
		Env:          execEnv,
		Tty:          true,
	}

	log.Debugf("running backup %s on %s with exec config %v", backupCmd, containerID, execBackupListOpts)

	// FIXME: avoid instantiating a new CLI
	dcli, err := command.NewDockerCli()
	if err != nil {
		return nil, err
	}

	out, err := container.RunExec(dcli, cl, containerID, &execBackupListOpts)
	if err != nil {
		return nil, err
	}

	return out, nil
}
