package app

import (
	"context"
	"fmt"
	"strings"

	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/client"
	"coopcloud.tech/abra/pkg/formatter"
	"coopcloud.tech/abra/pkg/log"
	"coopcloud.tech/abra/pkg/service"
	stack "coopcloud.tech/abra/pkg/upstream/stack"
	containerTypes "github.com/docker/docker/api/types/container"
	"github.com/urfave/cli/v3"
)

var appServicesCommand = cli.Command{
	Name:          "services",
	Aliases:       []string{"sr"},
	Usage:         "Display all services of an app",
	UsageText:     "abra app services <domain> [options]",
	Before:        internal.SubCommandBefore,
	ShellComplete: autocomplete.AppNameComplete,
	HideHelp:      true,
	Action: func(ctx context.Context, cmd *cli.Command) error {
		app := internal.ValidateApp(cmd)
		if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil {
			log.Fatal(err)
		}

		cl, err := client.New(app.Server)
		if err != nil {
			log.Fatal(err)
		}

		deployMeta, err := stack.IsDeployed(context.Background(), cl, app.StackName())
		if err != nil {
			log.Fatal(err)
		}

		if !deployMeta.IsDeployed {
			log.Fatalf("%s is not deployed?", app.Name)
		}

		filters, err := app.Filters(true, true)
		if err != nil {
			log.Fatal(err)
		}

		containers, err := cl.ContainerList(context.Background(), containerTypes.ListOptions{Filters: filters})
		if err != nil {
			log.Fatal(err)
		}

		table, err := formatter.CreateTable()
		if err != nil {
			log.Fatal(err)
		}

		headers := []string{"SERVICE (SHORT)", "SERVICE (LONG)", "IMAGE"}
		table.Headers(headers...)

		var rows [][]string
		for _, container := range containers {
			var containerNames []string
			for _, containerName := range container.Names {
				trimmed := strings.TrimPrefix(containerName, "/")
				containerNames = append(containerNames, trimmed)
			}

			serviceShortName := service.ContainerToServiceName(container.Names, app.StackName())
			serviceLongName := fmt.Sprintf("%s_%s", app.StackName(), serviceShortName)

			row := []string{
				serviceShortName,
				serviceLongName,
				formatter.RemoveSha(container.Image),
			}

			rows = append(rows, row)
		}

		table.Rows(rows...)

		if len(rows) > 0 {
			fmt.Println(table)
		}

		return nil
	},
}
