package writecache

import (
	"fmt"
	"os"

	common "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-lens/internal"
	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/local_object_storage/writecache/writecachebadger"
	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/local_object_storage/writecache/writecachebbolt"
	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/util/logger"
	objectSDK "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
	"github.com/spf13/cobra"
)

var inspectCMD = &cobra.Command{
	Use:   "inspect",
	Short: "Object inspection",
	Long:  `Inspect specific object in a write-cache.`,
	Run:   inspectFunc,
}

func init() {
	common.AddAddressFlag(inspectCMD, &vAddress)
	common.AddComponentPathFlag(inspectCMD, &vPath)
	common.AddOutputFileFlag(inspectCMD, &vOut)
	common.AddDBTypeFlag(inspectCMD, &vDBType)
}

func inspectFunc(cmd *cobra.Command, _ []string) {
	var data []byte

	switch vDBType {
	case "bbolt":
		db, err := writecachebbolt.OpenDB(vPath, true, os.OpenFile)
		common.ExitOnErr(cmd, common.Errf("could not open write-cache db: %w", err))
		defer db.Close()

		data, err = writecachebbolt.Get(db, []byte(vAddress))
		common.ExitOnErr(cmd, common.Errf("could not fetch object: %w", err))

	case "badger":
		log, err := logger.NewLogger(&logger.Prm{})
		common.ExitOnErr(cmd, common.Errf("could not create logger: %w", err))

		db, err := writecachebadger.OpenDB(vPath, true, log)
		common.ExitOnErr(cmd, common.Errf("could not open write-cache db: %w", err))

		data, err = writecachebadger.Get(db, []byte(vAddress))
		common.ExitOnErr(cmd, common.Errf("could not fetch object: %w", err))

	default:
		common.ExitOnErr(cmd, fmt.Errorf("invalid dbtype: %q (possible values: bbolt, badger)", vDBType))
	}

	var o objectSDK.Object
	common.ExitOnErr(cmd, common.Errf("could not unmarshal object: %w", o.Unmarshal(data)))

	common.PrintObjectHeader(cmd, o)
	common.WriteObjectToFile(cmd, vOut, data)
}