package inbox

import "testing"

func TestClaimAcquiresThreadLease(t *testing.T) {
	t.Parallel()

	dbPath := initCommandTestDB(t)
	threadID := sendPendingThread(t, dbPath, "leader", "worker-a", "Race claim", "Claim this task")

	claimOut := runInboxCommand(
		t,
		"--db", dbPath,
		"--json",
		"claim",
		"--agent", "worker-a",
		"--thread", threadID,
		"--lease-seconds", "300",
	)

	var claimResp map[string]any
	mustDecodeJSON(t, claimOut, &claimResp)
	if got := nestedString(t, claimResp, "data", "thread", "status"); got != "claimed" {
		t.Fatalf("expected claimed status, got %q", got)
	}
	if got := nestedString(t, claimResp, "data", "thread", "assigned_to"); got != "worker-a" {
		t.Fatalf("expected assigned_to worker-a, got %q", got)
	}
	if got := nestedString(t, claimResp, "data", "message", "kind"); got != "event" {
		t.Fatalf("expected event message kind, got %q", got)
	}
	if got := nestedString(t, claimResp, "data", "message", "summary"); got != "thread claimed" {
		t.Fatalf("expected summary thread claimed, got %q", got)
	}
}

func TestClaimRejectsWhenThreadMissing(t *testing.T) {
	t.Parallel()

	dbPath := initCommandTestDB(t)
	stdout, _, exitCode := executeInboxCommand(
		"--db", dbPath,
		"--json",
		"claim",
		"--agent", "worker-z",
		"--thread", "thr_missing",
	)
	if exitCode != 40 {
		t.Fatalf("expected exit code 40, got %d", exitCode)
	}
	assertErrorJSON(t, stdout, "not_found")
}

func TestClaimRejectsWhenThreadAlreadyClaimed(t *testing.T) {
	t.Parallel()

	dbPath := initCommandTestDB(t)
	threadID := sendPendingThread(t, dbPath, "leader", "worker-z", "Claimed task", "Already claimed")

	runInboxCommand(
		t,
		"--db", dbPath,
		"--json",
		"claim",
		"--agent", "worker-z",
		"--thread", threadID,
	)

	stdout, _, exitCode := executeInboxCommand(
		"--db", dbPath,
		"--json",
		"claim",
		"--agent", "worker-y",
		"--thread", threadID,
	)
	if exitCode != 20 {
		t.Fatalf("expected exit code 20, got %d", exitCode)
	}
	assertErrorJSON(t, stdout, "lease_conflict")
}

func TestClaimRecordsRequestedLeaseDuration(t *testing.T) {
	t.Parallel()

	dbPath := initCommandTestDB(t)
	threadID := sendPendingThread(t, dbPath, "leader", "worker-a", "Lease payload", "Verify lease payload")

	claimOut := runInboxCommand(
		t,
		"--db", dbPath,
		"--json",
		"claim",
		"--agent", "worker-a",
		"--thread", threadID,
		"--lease-seconds", "300",
	)

	var claimResp map[string]any
	mustDecodeJSON(t, claimOut, &claimResp)
	payload, ok := nestedValue(t, claimResp, "data", "message", "payload_json").(map[string]any)
	if !ok {
		t.Fatalf("expected payload_json object, got %#v", nestedValue(t, claimResp, "data", "message", "payload_json"))
	}
	leaseSeconds, ok := payload["lease_seconds"].(float64)
	if !ok || int(leaseSeconds) != 300 {
		t.Fatalf("expected lease_seconds 300, got %#v", payload["lease_seconds"])
	}
	leaseToken, _ := payload["lease_token"].(string)
	if leaseToken == "" {
		t.Fatalf("expected non-empty lease_token, got %#v", payload["lease_token"])
	}
}
