package locker

import (
	"sync"
	"testing"
)

func TestLocker(t *testing.T) {
	l := New()

	key := "test"
	locker1 := l.AssignLocker(key)
	locker2 := l.AssignLocker(key)

	if locker1 != locker2 {
		t.Error("Lockers for the same key are not identical")
	}

	l.ReleaseLocker(key)

	// Check that the locker for the same key is still the same after one release
	locker3 := l.AssignLocker(key)
	if locker1 != locker3 {
		t.Error("Locker for the same key changed after one release")
	}

	// Check that the locker for the same key changes after all releases
	l.ReleaseLocker(key)
	l.ReleaseLocker(key)
	locker4 := l.AssignLocker(key)
	if locker1 == locker4 {
		t.Error("Locker for the same key did not change after all releases")
	}
}

func TestConcurrency(t *testing.T) {
	l := New()
	key := "test"
	var wg sync.WaitGroup

	for i := 0; i < 20; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 1000; j++ {
				locker := l.AssignLocker(key)
				locker.Lock()

				locker.Unlock()
				l.ReleaseLocker(key)
			}
		}()
	}
	wg.Wait()
}
