package store

import "testing"

// ResolveGlobalFloor makes the DB-override-vs-env-fallback precedence explicit (the 9-minute-skew
// incident's root cause: a floor could be armed via the DB with the env still showing the old
// value). Companion red-proof: swap the precedence (env before DB) → the db-wins row fails.
func TestResolveGlobalFloor(t *testing.T) {
	t.Run("env only", func(t *testing.T) {
		s := newTestStore(t)
		s.SetDefaultMinControllerVersion("0.87.0")
		r := s.ResolveGlobalFloor()
		if r.Effective != "0.87.0" || r.Source != "env" || r.DBValue != "" || r.EnvValue != "0.87.0" {
			t.Fatalf("env-only: %+v", r)
		}
	})
	t.Run("db overrides env, both surfaced", func(t *testing.T) {
		s := newTestStore(t)
		s.SetDefaultMinControllerVersion("0.87.0")
		if err := s.SetGlobalMinControllerVersion("0.113.0"); err != nil {
			t.Fatal(err)
		}
		r := s.ResolveGlobalFloor()
		if r.Effective != "0.113.0" || r.Source != "db" {
			t.Fatalf("db must win: %+v", r)
		}
		if r.DBValue != "0.113.0" || r.EnvValue != "0.87.0" {
			t.Fatalf("both raw values must be surfaced: %+v", r)
		}
		// The precedence must match GetGlobalMinControllerVersion exactly (no forked rule).
		if got := s.GetGlobalMinControllerVersion(); got != r.Effective {
			t.Errorf("ResolveGlobalFloor.Effective=%q != GetGlobalMinControllerVersion=%q", r.Effective, got)
		}
	})
	t.Run("none", func(t *testing.T) {
		s := newTestStore(t)
		r := s.ResolveGlobalFloor()
		if r.Effective != "" || r.Source != "none" {
			t.Fatalf("none: %+v", r)
		}
	})
	t.Run("cleared db falls back to env", func(t *testing.T) {
		s := newTestStore(t)
		s.SetDefaultMinControllerVersion("0.87.0")
		_ = s.SetGlobalMinControllerVersion("0.113.0")
		_ = s.SetGlobalMinControllerVersion("") // clear the override
		r := s.ResolveGlobalFloor()
		if r.Effective != "0.87.0" || r.Source != "env" {
			t.Fatalf("cleared → env: %+v", r)
		}
	})
}
