/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 */
package imagecmd

import (
	"context"
	"time"

	"github.com/spf13/cobra"

	"mstore/pkg/repocli"
)

// CatalogImages
type CatalogImagesParams struct {
	Source string
}

type CatalogImagesResult struct {
	Repositories []string `json:"repositories"`
}

func (util *ImageUtil) CatalogImages(cmd *cobra.Command, args []string) {
	util.catalogImagesParams.Source = args[0]
	res, err := util.catalogImages(&util.commonImageParams, &util.catalogImagesParams)
	printResponse(res, err)
}

func (util *ImageUtil) catalogImages(common *CommonImageParams, params *CatalogImagesParams) (*CatalogImagesResult, error) {
	var err error
	res := &CatalogImagesResult{
		Repositories: make([]string, 0),
	}
	timeout := time.Duration(common.Timeout) * time.Second
	ctx, _ := context.WithTimeout(context.Background(), timeout)

	ref, err := repocli.NewReferer(params.Source)
	if err != nil {
		return res, err
	}
	ref.SetUserinfo(common.Username, common.Password)
	mw := repocli.NewBasicAuthMiddleware(ref.Userinfo())
	cli := repocli.NewClient(nil, mw)
	opres, err := cli.GetCatalog(ctx, ref.Raw())
	if err != nil {
		return res, err
	}
	res.Repositories = opres
	return res, err
}
