package mysql

import (
	"context"
	"testing"
	"time"

	"wucher/internal/queue"
)

func TestQueueIdempotencyStore_AcquireMarkCompletedRelease(t *testing.T) {
	db := openDBTestSQLite(t)
	if err := AutoMigrate(db); err != nil {
		t.Fatalf("auto migrate: %v", err)
	}

	baseTime := time.Date(2026, 3, 20, 10, 0, 0, 0, time.UTC)
	store := NewQueueIdempotencyStore(db, "queue:idempotency:")
	store.now = func() time.Time { return baseTime }

	ctx := context.Background()
	state, err := store.Acquire(ctx, "msg-1", time.Minute)
	if err != nil {
		t.Fatalf("acquire first: %v", err)
	}
	if state != queue.IdempotencyStateAcquired {
		t.Fatalf("expected acquired, got %s", state)
	}

	state, err = store.Acquire(ctx, "msg-1", time.Minute)
	if err != nil {
		t.Fatalf("acquire in-progress: %v", err)
	}
	if state != queue.IdempotencyStateInProgress {
		t.Fatalf("expected in progress, got %s", state)
	}

	if err := store.MarkCompleted(ctx, "msg-1", time.Hour); err != nil {
		t.Fatalf("mark completed: %v", err)
	}
	state, err = store.Acquire(ctx, "msg-1", time.Minute)
	if err != nil {
		t.Fatalf("acquire duplicate: %v", err)
	}
	if state != queue.IdempotencyStateDuplicate {
		t.Fatalf("expected duplicate, got %s", state)
	}

	if err := store.Release(ctx, "msg-1"); err != nil {
		t.Fatalf("release: %v", err)
	}
	state, err = store.Acquire(ctx, "msg-1", time.Minute)
	if err != nil {
		t.Fatalf("acquire after release: %v", err)
	}
	if state != queue.IdempotencyStateAcquired {
		t.Fatalf("expected acquired after release, got %s", state)
	}
}

func TestQueueIdempotencyStore_ReacquiresExpiredProcessingRecord(t *testing.T) {
	db := openDBTestSQLite(t)
	if err := AutoMigrate(db); err != nil {
		t.Fatalf("auto migrate: %v", err)
	}

	baseTime := time.Date(2026, 3, 20, 10, 0, 0, 0, time.UTC)
	store := NewQueueIdempotencyStore(db, "queue:idempotency:")
	store.now = func() time.Time { return baseTime }

	ctx := context.Background()
	state, err := store.Acquire(ctx, "msg-expired", time.Minute)
	if err != nil {
		t.Fatalf("acquire first: %v", err)
	}
	if state != queue.IdempotencyStateAcquired {
		t.Fatalf("expected acquired, got %s", state)
	}

	store.now = func() time.Time { return baseTime.Add(2 * time.Minute) }
	state, err = store.Acquire(ctx, "msg-expired", time.Minute)
	if err != nil {
		t.Fatalf("reacquire expired: %v", err)
	}
	if state != queue.IdempotencyStateAcquired {
		t.Fatalf("expected reacquired state, got %s", state)
	}
}
