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

import (
	"context"
	"fmt"
	"time"

	"github.com/spf13/cobra"

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

// FileInfo
type FileInfoParams struct {
	Filepath string
}
type FileInfoResult struct {
	File   *descr.File `json:"file,omitempty"`
	Size   int64       `json:"size,omitempty"`
	Digest string      `json:"digest,omitempty"`
}

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

func (util *FileUtil) fileInfo(common *CommonFileParams, params *FileInfoParams) (*FileInfoResult, error) {
	var err error
	res := &FileInfoResult{}
	ref, err := filecli.ParsePath(params.Filepath)
	if err != nil {
		return res, err
	}
	timeout := time.Duration(common.Timeout) * time.Second
	ctx, _ := context.WithTimeout(context.Background(), timeout)
	ref.SetUserinfo(common.Username, common.Password)

	mw := filecli.NewBasicAuthMiddleware(ref.Userinfo())
	cli := filecli.NewClient(nil, mw)
	exists, size, digest, err := cli.FileInfo(ctx, ref.Raw())
	if err != nil {
		return res, err
	}
	if !exists {
		err = fmt.Errorf("File %s not exists", params.Filepath)
		return res, err
	}
	res.Size = size
	res.Digest = digest
	return res, err
}
