package store

import (
	"context"
	"os"
	"strings"
	"testing"
	"time"
)

func TestPostgresLeadershipIsExclusiveAndRecoverable(t *testing.T) {
	databaseURL := strings.TrimSpace(os.Getenv("AI_GATEWAY_TEST_DATABASE_URL"))
	if databaseURL == "" {
		t.Skip("set AI_GATEWAY_TEST_DATABASE_URL to run PostgreSQL leadership integration tests")
	}
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()
	first, err := Connect(ctx, databaseURL)
	if err != nil {
		t.Fatal(err)
	}
	defer first.Close()
	second, err := Connect(ctx, databaseURL)
	if err != nil {
		t.Fatal(err)
	}
	defer second.Close()

	leader, acquired, err := first.TryAcquireSecurityEventHeartbeatLeadership(ctx)
	if err != nil || !acquired {
		t.Fatalf("first leadership acquired=%v err=%v", acquired, err)
	}
	defer leader.Release()
	if err := leader.KeepAlive(ctx); err != nil {
		t.Fatalf("leadership keepalive: %v", err)
	}
	blocked, acquired, err := second.TryAcquireSecurityEventHeartbeatLeadership(ctx)
	if err != nil {
		t.Fatal(err)
	}
	if acquired {
		blocked.Release()
		t.Fatal("second store acquired leadership while first store held it")
	}

	leader.Release()
	replacement, acquired, err := second.TryAcquireSecurityEventHeartbeatLeadership(ctx)
	if err != nil || !acquired {
		t.Fatalf("replacement leadership acquired=%v err=%v", acquired, err)
	}
	replacement.Release()
}
