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

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

	"github.com/spf13/cobra"

	"mstore/pkg/descr"
	"mstore/pkg/filecli"
)

// DeleteCollection
type DeleteCollectionParams struct {
	Path   string
	Detail bool
	Prefix bool
	Regexp bool
	DryRun bool
}

type DeleteCollectionResult struct {
	Files     []descr.File `json:"files,omitempty"`
	Filenames []string     `json:"filenames,omitempty"`
}

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

func (util *FileUtil) deleteCollection(common *CommonFileParams, params *DeleteCollectionParams) (*DeleteCollectionResult, error) {
	var err error
	res := &DeleteCollectionResult{
		Filenames: 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)
	mw := filecli.NewBasicAuthMiddleware(ref.Userinfo())
	ref.PathType(pathType(params.Regexp, params.Prefix))
	ref.DryRun(params.DryRun)
	cli := filecli.NewClient(nil, mw)
	list, err := cli.DeleteCollection(ctx, ref.Raw())
	if err != nil {
		return res, err
	}
	files := descr.NewFiles()
	err = json.Unmarshal(list, files.ArrayPtr())
	if err != nil {
		return res, err
	}
	if !params.Detail {
		res.Filenames = files.List()
	} else {
		res.Files = files.Array()
	}
	return res, err
}
