package database

import (
	"fmt"
	"log"
	"time"

	"github.com/ostafen/clover/v2"
	"github.com/ostafen/clover/v2/document"
	c "github.com/ostafen/clover/v2/query"
	badgerstore "github.com/ostafen/clover/v2/store/badger"
)

const (
	CollectionName = "shares"
)

type Handlers struct {
	DB *clover.DB
}

func InitDatabase() (*clover.DB, error) {
	store, err := badgerstore.Open("badgerdb")
	if err != nil {
		return nil, fmt.Errorf("failed to open BadgerDB store: %v", err)
	}

	db, err := clover.OpenWithStore(store)
	if err != nil {
		return nil, fmt.Errorf("failed to open CloverDB: %v", err)
	}

	// Ensure collection exists
	hasCollection, err := db.HasCollection(CollectionName)
	if err != nil {
		return nil, fmt.Errorf("failed to check collection: %v", err)
	}

	if !hasCollection {
		if err := db.CreateCollection(CollectionName); err != nil {
			return nil, fmt.Errorf("failed to create collection: %v", err)
		}
		if err := db.CreateIndex(CollectionName, "CreateDate"); err != nil {
			return nil, fmt.Errorf("failed to create index: %v", err)
		}
	}

	return db, nil
}

func GetHighestShareInRange(db *clover.DB, collection string, since time.Time) (*document.Document, error) {
	// Convert `since` to the format in `createdate`
	lower := since.Unix()
	upper := time.Now().Unix()

	// Filter by timestamp range
	criteria := c.Field("CreateDate").GtEq(fmt.Sprint(lower)).
		And(c.Field("CreateDate").LtEq(fmt.Sprint(upper)))

	// Query sorted by "sdiff" descending, limit 1
	results, err := db.FindAll(c.NewQuery(collection).
		Where(criteria).
		Sort(c.SortOption{Field: "SDiff", Direction: -1}).
		Limit(1))

	if err != nil || len(results) == 0 {
		return nil, err
	}
	return results[0], nil
}

func PrintAllHashes(db *clover.DB) {
	docs, err := db.FindAll(c.NewQuery(CollectionName))
	if err != nil {
		log.Fatalf("Failed to read from collection: %v", err)
	}

	for _, doc := range docs {
		hash := doc.Get("Hash")
		fmt.Println(hash)
	}
}