package main

import (
	"fmt"

	"github.com/spf13/cobra"
)

func pushCommand() *cobra.Command {
	var imageFlag string

	cmd := &cobra.Command{
		Use:   "push <service>",
		Short: "Push container images to the registry",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			cfg, err := loadCfg()
			if err != nil {
				return err
			}

			svc, err := cfg.FindService(args[0])
			if err != nil {
				return err
			}

			images := svc.Images
			if imageFlag != "" {
				images = []string{imageFlag}
			}

			var pushed []string
			for _, image := range images {
				ref := cfg.ImageRef(image) + ":latest"
				if err := run("podman", "push", ref); err != nil {
					return fmt.Errorf("push %s: %w", image, err)
				}
				pushed = append(pushed, ref)
			}

			fmt.Printf("\nPushed %d image(s):\n", len(pushed))
			for _, ref := range pushed {
				fmt.Printf("  %s\n", ref)
			}
			return nil
		},
	}

	cmd.Flags().StringVar(&imageFlag, "image", "", "push only this image")
	return cmd
}
