package inbox

import "testing"

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

	dbPath := initCommandTestDB(t)
	threadID := sendPendingThread(t, dbPath, "leader", "worker-c", "Renew lease", "Need renew coverage")

	runInboxCommand(
		t,
		"--db", dbPath,
		"--json",
		"claim",
		"--agent", "worker-c",
		"--thread", threadID,
		"--lease-seconds", "300",
	)

	renewOut := runInboxCommand(
		t,
		"--db", dbPath,
		"--json",
		"renew",
		"--agent", "worker-c",
		"--thread", threadID,
		"--lease-seconds", "600",
	)

	var renewResp map[string]any
	mustDecodeJSON(t, renewOut, &renewResp)
	if got := nestedString(t, renewResp, "data", "thread", "status"); got != "claimed" {
		t.Fatalf("expected status to stay claimed, got %q", got)
	}
	if got := nestedString(t, renewResp, "data", "message", "kind"); got != "event" {
		t.Fatalf("expected event message kind, got %q", got)
	}
	if got := nestedString(t, renewResp, "data", "message", "summary"); got != "lease renewed" {
		t.Fatalf("expected lease renewed summary, got %q", got)
	}
	payload, ok := nestedValue(t, renewResp, "data", "message", "payload_json").(map[string]any)
	if !ok {
		t.Fatalf("expected payload_json object, got %#v", nestedValue(t, renewResp, "data", "message", "payload_json"))
	}
	leaseSeconds, ok := payload["lease_seconds"].(float64)
	if !ok || int(leaseSeconds) != 600 {
		t.Fatalf("expected lease_seconds 600, got %#v", payload["lease_seconds"])
	}
	leaseToken, _ := payload["lease_token"].(string)
	if leaseToken == "" {
		t.Fatalf("expected non-empty lease_token, got %#v", payload["lease_token"])
	}
}

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

	dbPath := initCommandTestDB(t)
	threadID := sendPendingThread(t, dbPath, "leader", "worker-c", "Renew non-owner", "Reject non-owner renew")

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

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

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

	dbPath := initCommandTestDB(t)
	threadID := sendPendingThread(t, dbPath, "leader", "worker-c", "Renew without lease", "Should fail without active lease")

	stdout, _, exitCode := executeInboxCommand(
		"--db", dbPath,
		"--json",
		"renew",
		"--agent", "worker-c",
		"--thread", threadID,
		"--lease-seconds", "600",
	)
	if exitCode != 30 {
		t.Fatalf("expected exit code 30, got %d", exitCode)
	}
	assertErrorJSON(t, stdout, "invalid_state")
}
