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

import (
	"context"
	"encoding/json"
	"time"

	"github.com/spf13/cobra"

	"mstore/pkg/filecli"
)

// ListCollections
type ListCollectionsParams struct {
	Path   string
	Prefix bool
	Regexp bool
}

type ListCollectionsResult struct {
	Collections []string `json:"collections,omitempty"`
}

func (util *FileUtil) ListCollections(cmd *cobra.Command, args []string) {
	util.listCollectionsParams.Path = args[0]
	res, err := util.listCollections(&util.commonFileParams, &util.listCollectionsParams)
	printResponse(res, err)
}

func (util *FileUtil) listCollections(common *CommonFileParams, params *ListCollectionsParams) (*ListCollectionsResult, error) {
	var err error
	res := &ListCollectionsResult{
		Collections: make([]string, 0),
	}

	timeout := time.Duration(common.Timeout) * time.Second
	ctx, _ := context.WithTimeout(context.Background(), timeout)
	ref, err := filecli.ParsePath(params.Path)
	if err != nil {
		return res, err
	}
	ref.SetUserinfo(common.Username, common.Password)
	ref.PathType(pathType(params.Regexp, params.Prefix))
	mw := filecli.NewBasicAuthMiddleware(ref.Userinfo())
	cli := filecli.NewClient(nil, mw)
	list, err := cli.ListCollections(ctx, ref.Raw())
	if err != nil {
		return res, err
	}
	collections := make([]string, 0)
	err = json.Unmarshal(list, &collections)
	if err != nil {
		return res, err
	}
	res.Collections = collections
	return res, err
}
