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

	"github.com/spf13/cobra"

	"mstore/pkg/filecli"
)

// PutFile
type PutFileParams struct {
	Source string
	Dest   string
}
type PutFileResult struct{}

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

func (util *FileUtil) putFile(common *CommonFileParams, params *PutFileParams) (*PutFileResult, error) {
	var err error
	res := &PutFileResult{}

	file, err := os.OpenFile(params.Source, os.O_RDONLY, 0)
	if err != nil {
		return res, err
	}
	defer file.Close()
	stat, err := file.Stat()
	if err != nil {
		return res, err
	}
	timeout := time.Duration(common.Timeout) * time.Second
	ctx, _ := context.WithTimeout(context.Background(), timeout)
	ref, err := filecli.ParsePath(params.Dest)
	if err != nil {
		return res, err
	}
	ref.SetUserinfo(common.Username, common.Password)

	mw := filecli.NewBasicAuthMiddleware(ref.Userinfo())
	cli := filecli.NewClient(nil, mw)
	err = cli.PutFile(ctx, ref.Raw(), file, stat.Size())
	if err != nil {
		return res, err
	}
	return res, err
}
