package systemtables

import (
	"fmt"
	"sync/atomic"
	"time"
)

const schemaVersionMod = uint64(1_000_000_000_000)

var schemaVersionCounter uint64
var schemaVersionValue atomic.Value

func init() {
	seed := uint64(time.Now().UnixNano()) % schemaVersionMod
	atomic.StoreUint64(&schemaVersionCounter, seed)
	schemaVersionValue.Store(formatSchemaVersion(seed))
}

// CurrentSchemaVersion returns the current schema_version UUID string.
func CurrentSchemaVersion() string {
	if v := schemaVersionValue.Load(); v != nil {
		return v.(string)
	}
	return formatSchemaVersion(0)
}

// BumpSchemaVersion advances the schema_version UUID string.
func BumpSchemaVersion() string {
	next := atomic.AddUint64(&schemaVersionCounter, 1)
	version := formatSchemaVersion(next)
	schemaVersionValue.Store(version)
	return version
}

func formatSchemaVersion(value uint64) string {
	return fmt.Sprintf("00000000-0000-0000-0000-%012d", value%schemaVersionMod)
}
