package list

import (
	"context"
	"flag"
	"fmt"

	"gitlab.com/gitlab-org/fleeting/fleeting-artifact/pkg/client"
)

type listCmd struct {
	fs *flag.FlagSet
}

func New() *listCmd {
	c := &listCmd{}
	c.fs = flag.NewFlagSet("list", flag.ExitOnError)
	c.fs.Usage = func() {
		fmt.Fprintln(c.fs.Output(), c.fs.Name(), "NAME[:VERSION_CONSTRAINT]")
		fmt.Fprintf(c.fs.Output(), "\n  Lists versions filtered by the version constraint provided.\n")
		c.fs.PrintDefaults()
	}

	return c
}

func (cmd *listCmd) Command() *flag.FlagSet {
	return cmd.fs
}

func (cmd *listCmd) Execute(ctx context.Context) error {
	if len(cmd.fs.Args()) < 1 {
		return flag.ErrHelp
	}

	c, err := client.New()
	if err != nil {
		return fmt.Errorf("creating client: %w", err)
	}

	versions, err := c.List(ctx, cmd.fs.Arg(0))
	if err != nil {
		return fmt.Errorf("listing versions: %w", err)
	}

	for _, version := range versions {
		fmt.Println(version)
	}

	return nil
}
