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

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

	"github.com/spf13/cobra"

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

// ListFiles
type ListFilesParams struct {
	Filepath string
	Detail   bool
	Prefix   bool
	Regexp   bool
}

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

func (util *FileUtil) ListFiles(cmd *cobra.Command, args []string) {
	util.listFilesParams.Filepath = args[0]
	res, err := util.listFiles(&util.commonFileParams, &util.listFilesParams)
	printResponse(res, err)
}

func (util *FileUtil) listFiles(common *CommonFileParams, params *ListFilesParams) (*ListFilesResult, error) {
	var err error
	res := &ListFilesResult{}
	timeout := time.Duration(common.Timeout) * time.Second
	ctx, _ := context.WithTimeout(context.Background(), timeout)
	ref, err := filecli.ParsePath(params.Filepath)
	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.ListFiles(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
}

func pathType(regex, prefix bool) string {
	switch {
	case regex:
		return filecli.PathTypeRegexp
	case prefix:
		return filecli.PathTypePrefix
	default:
	}
	return filecli.PathTypeIdentic
}
