/*
 * 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"
	"os"
	"path/filepath"
	"time"

	"github.com/spf13/cobra"

	"mstore/pkg/filecli"
)

// GetFile
type GetFileParams struct {
	Source string
	Dest   string
}

func (util *FileUtil) GetFile(cmd *cobra.Command, args []string) {
	util.getFileParams.Source = args[0]
	util.getFileParams.Dest = args[1]
	res, err := util.getFile(&util.commonFileParams, &util.getFileParams)
	printResponse(res, err)
}

type GetFileResult struct{}

func (util *FileUtil) getFile(common *CommonFileParams, params *GetFileParams) (*GetFileResult, error) {
	var err error
	res := &GetFileResult{}

	err = os.MkdirAll(filepath.Dir(params.Dest), 0750)
	if err != nil {
		return res, err
	}
	file, err := os.OpenFile(params.Dest, os.O_WRONLY|os.O_CREATE, 0640)
	if err != nil {
		return res, err
	}
	defer file.Close()

	timeout := time.Duration(common.Timeout) * time.Second
	ctx, _ := context.WithTimeout(context.Background(), timeout)
	ref, err := filecli.ParsePath(params.Source)
	if err != nil {
		return res, err
	}
	ref.SetUserinfo(common.Username, common.Password)
	mw := filecli.NewBasicAuthMiddleware(ref.Userinfo())
	cli := filecli.NewClient(nil, mw)
	_, err = cli.GetFile(ctx, ref.Raw(), file)
	if err != nil {
		return res, err
	}
	return res, err
}
