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/spf13/cobra"
)

var AppServicesCommand = &cobra.Command{
	Use:     "services <domain> [flags]",
	Aliases: []string{"sr"},
	Short:   "Display all services of an app",
	Args:    cobra.ExactArgs(1),
	ValidArgsFunction: func(
		cmd *cobra.Command,
		args []string,
		toComplete string) ([]string, cobra.ShellCompDirective) {
		return autocomplete.AppNameComplete()
	},
	Run: func(cmd *cobra.Command, args []string) {
		app := internal.ValidateApp(args)

		if err := app.Recipe.Ensure(internal.GetEnsureContext()); 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)"}
		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,
			}

			rows = append(rows, row)
		}

		table.Rows(rows...)

		if len(rows) > 0 {
			if err := formatter.PrintTable(table); err != nil {
				log.Fatal(err)
			}
		}
	},
}
