/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 *
 * This work is published and licensed under a Creative Commons
 * Attribution-NonCommercial-NoDerivatives 4.0 International License.
 *
 * Distribution of this work is permitted, but commercial use and
 * modifications are strictly prohibited.
 */
package filecmd

import (
	"context"
	"encoding/json"
	"fmt"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"time"

	"github.com/spf13/cobra"

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

// ExportFiles
type ExportFilesParams struct {
	Filepath string
	Detail   bool
	Prefix   bool
	Regexp   bool
	Dest     string
}

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

func (util *FileUtil) ExportFiles(cmd *cobra.Command, args []string) {
	util.exportFilesParams.Filepath = args[0]
	util.exportFilesParams.Dest = args[1]
	res, err := util.exportFiles(&util.commonFileParams, &util.exportFilesParams)
	printResponse(res, err)
}

func (util *FileUtil) exportFiles(common *CommonFileParams, params *ExportFilesParams) (*ExportFilesResult, error) {
	var err error
	res := &ExportFilesResult{}

	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)
	mw := filecli.NewBasicAuthMiddleware(ref.Userinfo())
	cli := filecli.NewClient(nil, mw)
	list, err := cli.ListFiles(ctx, ref.Raw())
	if err != nil {
		return res, err
	}
	files := make([]descr.File, 0)
	err = json.Unmarshal(list, &files)
	if err != nil {
		return res, err
	}

	exported := make([]descr.File, 0)
	for _, descr := range files {
		destdir := filepath.Join(params.Dest, descr.Collection)
		err = os.MkdirAll(destdir, 0750)
		if err != nil {
			return res, err
		}
		destpath := filepath.Join(params.Dest, descr.Collection, descr.Name)
		destfile, err := os.OpenFile(destpath, os.O_WRONLY|os.O_CREATE, 0640)
		if err != nil {
			return res, err
		}
		defer destfile.Close()

		timeout := time.Duration(common.Timeout) * time.Second
		ctx, _ := context.WithTimeout(context.Background(), timeout)
		ref.SetResource(filepath.Join(descr.Collection, descr.Name))
		mw := filecli.NewBasicAuthMiddleware(ref.Userinfo())
		cli := filecli.NewClient(nil, mw)
		_, err = cli.GetFile(ctx, ref.Raw(), destfile)
		if err != nil {

			fmt.Printf("- %s: error %v\n", ref.Raw(), err)
			err = nil
		} else {
			fmt.Printf("- %s: ok\n", ref.Raw())
			exported = append(exported, descr)
		}
	}
	if params.Detail {
		res.Files = exported
	} else {
		files := descr.NewFiles()
		files.Set(exported)
		res.Filenames = files.List()
	}
	return res, err
}

func makeFileURI(hosturi, collection, name string) (string, error) {
	var err error
	var res string
	uri, err := url.Parse(hosturi)
	if err != nil {
		return res, err
	}
	uri.Path = path.Join(collection, name)
	res = uri.String()
	return res, err
}
