import test from "node:test";
import assert from "node:assert/strict";

import {
  buildZillowAddressSlug,
  parseAddressIdentity,
  scoreAddressCandidate,
} from "./real-estate-address.js";

test("parseAddressIdentity detects unit numbers when present", () => {
  const identity = parseAddressIdentity("4141 Whiteley Dr Apt 204, Corpus Christi, TX 78418");

  assert.equal(identity.streetWithoutUnit, "4141 Whiteley Dr");
  assert.equal(identity.unitValue, "204");
  assert.equal(identity.hasUnit, true);
  assert.deepEqual(identity.streetTokens, ["4141", "whiteley"]);
});

test("parseAddressIdentity supports plain single-family style addresses with no unit", () => {
  const identity = parseAddressIdentity("1201 E Iberian Ct, Granbury, TX 76048");

  assert.equal(identity.unitValue, null);
  assert.equal(identity.hasUnit, false);
  assert.deepEqual(identity.streetTokens, ["1201", "e", "iberian"]);
});

test("buildZillowAddressSlug keeps unit identifiers in the slug", () => {
  assert.equal(
    buildZillowAddressSlug("4141 Whiteley Dr Apt 204, Corpus Christi, TX 78418"),
    "4141-Whiteley-Dr-Apt-204-Corpus-Christi-TX-78418"
  );
});

test("scoreAddressCandidate rejects a wrong unit on the same street", () => {
  const identity = parseAddressIdentity("4141 Whiteley Dr Apt 204, Corpus Christi, TX 78418");
  const good = scoreAddressCandidate(
    identity,
    "https://www.zillow.com/homedetails/4141-Whiteley-Dr-Apt-204-Corpus-Christi-TX-78418/123_zpid/"
  );
  const bad = scoreAddressCandidate(
    identity,
    "https://www.zillow.com/homedetails/4141-Whiteley-Dr-Apt-305-Corpus-Christi-TX-78418/456_zpid/"
  );

  assert.equal(good.matched, true);
  assert.equal(good.unitMatched, true);
  assert.equal(bad.matched, false);
  assert.equal(bad.unitMatched, false);
});

test("scoreAddressCandidate still matches plain addresses with no unit", () => {
  const identity = parseAddressIdentity("1201 E Iberian Ct, Granbury, TX 76048");
  const result = scoreAddressCandidate(
    identity,
    "1201 E Iberian Ct Granbury, TX 76048 For Sale, Residential"
  );

  assert.equal(result.matched, true);
});
