package stats

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/ostafen/clover/v2"

	"pool-stats/database"
	"pool-stats/models"
)

func parseCreatedate(createdate string) time.Time {
	parts := strings.Split(createdate, ",")
	if len(parts) == 2 {
		sec, _ := strconv.ParseInt(parts[0], 10, 64)
		nsec, _ := strconv.ParseInt(parts[1], 10, 64)
		return time.Unix(sec, nsec)
	}
	return time.Time{}
}

func humanDiff(diff float64) string {
	units := []string{"", "K", "M", "G", "T"}
	i := 0
	for diff >= 1000 && i < len(units)-1 {
		diff /= 1000
		i++
	}
	return fmt.Sprintf("%.2f%s", diff, units[i])
}

func GetStats(db *clover.DB) ([]models.ShareStat, error) {
	now := time.Now()
	ranges := []struct {
		Label string
		Since time.Time
	}{
		{"Past Hour", now.Add(-1 * time.Hour)},
		{"Past 24h", now.Add(-24 * time.Hour)},
		{"Past 7d", now.Add(-7 * 24 * time.Hour)},
	}

	stats := []models.ShareStat{}

	// All-time highest
	doc, _ := database.GetHighestShareInRange(db, database.CollectionName, time.Unix(0, 0))
	if doc != nil {
		stats = append(stats, models.ShareStat{
			Label: "All Time",
			Diff:  humanDiff(doc.Get("SDiff").(float64)),
			Time:  parseCreatedate(doc.Get("CreateDate").(string)).Format(time.RFC822),
		})
	}

	for _, r := range ranges {
		doc, _ := database.GetHighestShareInRange(db, database.CollectionName, r.Since)
		if doc != nil {
			stats = append(stats, models.ShareStat{
				Label: r.Label,
				Diff:  humanDiff(doc.Get("SDiff").(float64)),
				Time:  parseCreatedate(doc.Get("CreateDate").(string)).Format(time.RFC822),
			})
		} else {
			stats = append(stats, models.ShareStat{Label: r.Label, Diff: "-", Time: "-"})
		}
	}

	return stats, nil
}