import assert from "node:assert/strict"; import test from "node:test"; import { buildLeadDiscoveryLeadRecord, buildLeadDiscoveryCounters, canStartAgentRun, isStalePendingAgentRun, getLeadDiscoveryContactStatus, } from "../lib/lead-discovery-run"; test("agent run guard ignores stale pending runs but blocks active runs", () => { const now = Date.UTC(2026, 5, 4, 13, 20, 0); assert.equal(canStartAgentRun([{ status: "succeeded" }], now), true); assert.equal( canStartAgentRun([{ status: "pending", updatedAt: now - 20 * 60 * 1000 }], now), true, ); assert.equal( canStartAgentRun([{ status: "pending", updatedAt: now - 30_000 }], now), false, ); assert.equal( canStartAgentRun([{ status: "failed" }, { status: "running" }], now), false, ); }); test("stale pending runs are older than the discovery startup grace period", () => { const now = Date.UTC(2026, 5, 4, 13, 20, 0); assert.equal( isStalePendingAgentRun({ status: "pending", updatedAt: now - 11 * 60 * 1000 }, now), true, ); assert.equal( isStalePendingAgentRun({ status: "pending", updatedAt: now - 9 * 60 * 1000 }, now), false, ); assert.equal( isStalePendingAgentRun({ status: "running", updatedAt: now - 60 * 60 * 1000 }, now), false, ); }); test("lead discovery counters preserve audit and outreach counters", () => { const counters = buildLeadDiscoveryCounters({ leadsFound: 12, leadsCreated: 3, errors: 1, }); assert.deepEqual(counters, { leadsFound: 12, leadsCreated: 3, auditsCreated: 0, outreachPrepared: 0, errors: 1, }); }); test("lead discovery contact status separates leads without any contact route", () => { assert.equal( getLeadDiscoveryContactStatus({ websiteDomain: null, phone: null }), "missing_contact", ); assert.equal( getLeadDiscoveryContactStatus({ websiteDomain: "example.de", phone: null }), "new", ); assert.equal( getLeadDiscoveryContactStatus({ websiteDomain: null, phone: "030 123" }), "new", ); }); test("lead discovery lead record keeps raw website url and normalized domain", () => { const record = buildLeadDiscoveryLeadRecord({ campaignId: "campaign-1", runId: "run-1", niche: "Restaurant", postalCode: "10115", now: 1717480000000, candidate: { placeId: "place-1", businessName: "Beispiel GmbH", address: "Hauptstraße 1", websiteUrl: "https://www.example.de/path", websiteDomain: "example.de", phone: "+49 30 123", rating: 4.5, userRatingCount: 12, businessStatus: "OPERATIONAL", googleTypes: ["restaurant"], googlePrimaryType: "restaurant", googleMapsUrl: "https://maps.google.com/place-1", sourceProvider: "google_places", sourceFetchedAt: 1717480001000, }, }); assert.equal(record.websiteUrl, "https://www.example.de/path"); assert.equal(record.websiteDomain, "example.de"); assert.equal(record.googleRating, 4.5); assert.equal(record.googleUserRatingCount, 12); assert.equal(record.sourceFetchedAt, 1717480001000); });