package cli

import (
	"github.com/spf13/cobra"

	"github.com/tidbcloud/observability/vm-migration/internal/tenants"
)

// newTenantsMergeCmd returns the tenants merge command.
//
// Merges tenants JSON files (archive wins over k8s), sorts by account/project,
// and writes a flat array for plan compile.
func newTenantsMergeCmd() *cobra.Command {
	var o tenants.MergeOptions
	cmd := &cobra.Command{
		Use:   "merge",
		Short: "Merge tenant list files into a flat array",
		Long: `Reads one or more tenants-*.json files (each in the canonical
{"total": N, "tenants": [...]} wire shape written by tenants dedicated /
essential), merges by tenant ID (archive sources win over k8s), sorts
numerically by accountID then projectID, and writes a flat JSON array
of tenant id strings to --output.

The output is consumed by ` + "`plan compile --tenants`" + `. The compiled
plan embeds the flat tenant list; prepare later expands it into runtime files.`,
		Args:         cobra.NoArgs,
		SilenceUsage: true,
		Example: `  # Merge the per-source lists of one environment into tenants.json
  vm-migration tenants merge \
    --input tenants-dedicated-k8s.json \
    --input tenants-dedicated-s3.json \
    --input tenants-essential.json \
    --output tenants.json`,
		RunE: func(cmd *cobra.Command, args []string) error {
			return tenants.RunMerge(cmd.Context(), o, cmd.OutOrStdout(), cmd.ErrOrStderr())
		},
	}
	cmd.Flags().StringArrayVar(&o.Inputs, "input", nil,
		"Input tenants JSON file (repeatable; expects {total, tenants: [...]}) (required)")
	cmd.Flags().StringVar(&o.Output, "output", "",
		"Output path for the merged flat array (default: stdout)")
	mustMarkRequired(cmd, "input")
	return cmd
}
