package cache

import (
	"encoding/json"
	"time"

	"github.com/dgraph-io/badger/v2"
	"go.fifitido.net/ytdl-web/pkg/ytdl/metadata"
)

type MetadataCache interface {
	Get(key string) (*metadata.Metadata, error)
	Set(key string, value *metadata.Metadata, ttl time.Duration) error
}

type DefaultMetadataCache struct {
	db *badger.DB
}

func NewDefaultMetadataCache(db *badger.DB) *DefaultMetadataCache {
	return &DefaultMetadataCache{
		db: db,
	}
}
func (c *DefaultMetadataCache) Get(key string) (*metadata.Metadata, error) {
	value := &metadata.Metadata{}
	err := c.db.View(func(txn *badger.Txn) error {
		item, err := txn.Get([]byte(key))
		if err != nil {
			return err
		}

		return item.Value(func(val []byte) error {
			return json.Unmarshal(val, value)
		})
	})
	return value, err
}

func (c *DefaultMetadataCache) Set(key string, value *metadata.Metadata, ttl time.Duration) error {
	return c.db.Update(func(txn *badger.Txn) error {
		data, err := json.Marshal(value)
		if err != nil {
			return err
		}
		e := badger.NewEntry([]byte(key), data).WithTTL(ttl)
		return txn.SetEntry(e)
	})
}
