package state

import (
	"context"
	"log/slog"
	"strconv"

	"tangled.org/core/appview/cache"
	"tangled.org/core/tid"
)

func legacyCursorTID(oldVal string) (string, bool) {
	nanos, err := strconv.ParseInt(oldVal, 10, 64)
	if err != nil {
		return "", false
	}
	gen := tid.MonotonicGenerator{}
	return gen.FromNanos(nanos), true
}

func migrateLegacyCursor(ctx context.Context, logger *slog.Logger, c *cache.Cache, host, newPrefix string) {
	if c == nil {
		return
	}
	oldKey := "cursor:" + host
	newKey := "cursor:" + newPrefix + ":" + host

	if n, _ := c.Exists(ctx, newKey).Result(); n > 0 {
		return
	}

	oldVal, err := c.Get(ctx, oldKey).Result()
	if err != nil || oldVal == "" {
		return
	}

	newTid, ok := legacyCursorTID(oldVal)
	if !ok {
		return
	}

	if err := c.Set(ctx, newKey, newTid, 0).Err(); err != nil {
		logger.Warn("cursor backfill: set new key failed", "host", host, "err", err)
		return
	}
	if err := c.Del(ctx, oldKey).Err(); err != nil {
		logger.Warn("cursor backfill: delete old key failed", "host", host, "err", err)
	}
	logger.Info("cursor backfill: migrated", "host", host, "nanos", oldVal, "tid", newTid, "prefix", newPrefix)
}
