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

import { resolvePublicRecords } from "../src/public-records.js";

const geocoderPayload = {
  result: {
    addressMatches: [
      {
        matchedAddress: "4141 WHITELEY DR, CORPUS CHRISTI, TX, 78418",
        coordinates: { x: -97.30174, y: 27.613668 },
        geographies: {
          States: [{ NAME: "Texas", STUSAB: "TX", STATE: "48" }],
          Counties: [{ NAME: "Nueces County", COUNTY: "355", GEOID: "48355" }],
          "2020 Census Blocks": [{ GEOID: "483550031013005" }]
        }
      }
    ]
  }
};

const countyIndexHtml = `
<ul>
  <li><a href="nueces.php">178 Nueces</a></li>
</ul>
`;

const countyPageHtml = `
<div class="medium-6 small-12 columns">
  <h3>Appraisal District</h3>
  <p class="file-info">Last Updated: 08/13/2025</p>
  <h4>Chief Appraiser: Debra Morin, Interim</h4>
  <p>
    <strong>Phone:</strong> <a href="tel:361-881-9978">361-881-9978</a><br />
    <strong>Email:</strong> <a href="mailto:info@nuecescad.net">info@nuecescad.net</a><br />
    <strong>Website:</strong> <a href="http://www.ncadistrict.com/">www.ncadistrict.com</a>
  </p>
  <h4>Mailing Address</h4>
  <p>201 N. Chaparral St.<br />Corpus Christi, TX 78401-2503</p>
</div>
<div class="medium-6 small-12 columns">
  <h3>Tax Assessor/Collector</h3>
  <p class="file-info">Last Updated: 02/18/2025</p>
  <h4>Tax Assessor-Collector: Kevin Kieschnick</h4>
  <p>
    <strong>Phone:</strong> <a href="tel:361-888-0307">361-888-0307</a><br />
    <strong>Email:</strong> <a href="mailto:nueces.tax@nuecesco.com">nueces.tax@nuecesco.com</a><br />
    <strong>Website:</strong> <a href="http://www.nuecesco.com">www.nuecesco.com</a>
  </p>
  <h4>Street Address</h4>
  <p>901 Leopard St., Room 301<br />Corpus Christi, Texas 78401-3602</p>
</div>
`;

const fakeFetchText = async (url: string): Promise<string> => {
  if (url.includes("geocoding.geo.census.gov")) {
    return JSON.stringify(geocoderPayload);
  }
  if (url.endsWith("/county-directory/")) {
    return countyIndexHtml;
  }
  if (url.endsWith("/county-directory/nueces.php")) {
    return countyPageHtml;
  }
  throw new Error(`Unexpected URL: ${url}`);
};

test("resolvePublicRecords uses Census and Texas county directory", async () => {
  const payload = await resolvePublicRecords("4141 Whiteley Dr, Corpus Christi, TX 78418", {
    parcelId: "14069438",
    listingGeoId: "233290",
    listingSourceUrl: "https://www.zillow.com/homedetails/example",
    fetchText: fakeFetchText
  });

  assert.equal(payload.county.name, "Nueces County");
  assert.equal(payload.state.code, "TX");
  assert.equal(payload.appraisalDistrict?.Website, "http://www.ncadistrict.com/");
  assert.equal(payload.taxAssessorCollector?.Email, "nueces.tax@nuecesco.com");
  assert.equal(payload.sourceIdentifierHints.parcelId, "14069438");
  assert.match(payload.lookupRecommendations.join(" "), /listing geo IDs as regional hints only/i);
});

test("resolvePublicRecords falls back to coordinate geocoding when Census address lookup misses", async () => {
  const coordinatePayload = {
    result: {
      geographies: {
        States: [{ NAME: "Texas", STUSAB: "TX", STATE: "48" }],
        Counties: [{ NAME: "Nueces County", COUNTY: "355", GEOID: "48355" }],
        "2020 Census Blocks": [{ GEOID: "483550031013005" }]
      }
    }
  };

  const fallbackFetchText = async (url: string): Promise<string> => {
    if (url.includes("geocoding.geo.census.gov") && url.includes("onelineaddress")) {
      return JSON.stringify({ result: { addressMatches: [] } });
    }
    if (url.includes("nominatim.openstreetmap.org/search")) {
      return JSON.stringify([
        {
          lat: "27.708000",
          lon: "-97.360000",
          display_name: "1011 Ennis Joslin Rd Apt 235, Corpus Christi, TX 78412"
        }
      ]);
    }
    if (url.includes("geocoding.geo.census.gov") && url.includes("geographies/coordinates")) {
      return JSON.stringify(coordinatePayload);
    }
    if (url.endsWith("/county-directory/")) {
      return countyIndexHtml;
    }
    if (url.endsWith("/county-directory/nueces.php")) {
      return countyPageHtml;
    }
    throw new Error(`Unexpected URL: ${url}`);
  };

  const payload = await resolvePublicRecords(
    "1011 Ennis Joslin Rd APT 235, Corpus Christi, TX 78412",
    {
      fetchText: fallbackFetchText
    }
  );

  assert.equal(
    payload.matchedAddress,
    "1011 Ennis Joslin Rd Apt 235, Corpus Christi, TX 78412"
  );
  assert.equal(payload.county.name, "Nueces County");
  assert.equal(payload.state.code, "TX");
  assert.equal(payload.latitude, 27.708);
  assert.equal(payload.longitude, -97.36);
  assert.match(
    payload.lookupRecommendations.join(" "),
    /fallback geocoder/i
  );
});

test("resolvePublicRecords retries fallback geocoding without the unit suffix", async () => {
  const seenFallbackQueries: string[] = [];
  const coordinatePayload = {
    result: {
      geographies: {
        States: [{ NAME: "Texas", STUSAB: "TX", STATE: "48" }],
        Counties: [{ NAME: "Nueces County", COUNTY: "355", GEOID: "48355" }],
        "2020 Census Blocks": [{ GEOID: "483550031013005" }]
      }
    }
  };

  const retryingFetchText = async (url: string): Promise<string> => {
    if (url.includes("geocoding.geo.census.gov") && url.includes("onelineaddress")) {
      return JSON.stringify({ result: { addressMatches: [] } });
    }
    if (url.includes("nominatim.openstreetmap.org/search")) {
      const query = new URL(url).searchParams.get("q") || "";
      seenFallbackQueries.push(query);
      if (query.includes("APT 235")) {
        return "[]";
      }
      if (query === "1011 Ennis Joslin Rd, Corpus Christi, TX 78412") {
        return JSON.stringify([
          {
            lat: "27.6999080",
            lon: "-97.3338107",
            display_name: "Ennis Joslin Road, Corpus Christi, Nueces County, Texas, 78412, United States"
          }
        ]);
      }
    }
    if (url.includes("geocoding.geo.census.gov") && url.includes("geographies/coordinates")) {
      return JSON.stringify(coordinatePayload);
    }
    if (url.endsWith("/county-directory/")) {
      return countyIndexHtml;
    }
    if (url.endsWith("/county-directory/nueces.php")) {
      return countyPageHtml;
    }
    throw new Error(`Unexpected URL: ${url}`);
  };

  const payload = await resolvePublicRecords(
    "1011 Ennis Joslin Rd APT 235, Corpus Christi, TX 78412",
    {
      fetchText: retryingFetchText
    }
  );

  assert.deepEqual(seenFallbackQueries, [
    "1011 Ennis Joslin Rd APT 235, Corpus Christi, TX 78412",
    "1011 Ennis Joslin Rd, Corpus Christi, TX 78412"
  ]);
  assert.equal(payload.county.name, "Nueces County");
  assert.equal(payload.state.code, "TX");
});

test("resolvePublicRecords enriches official CAD property facts when a supported CAD detail source is available", async () => {
  const fetchedUrls: string[] = [];
  const enrichedFetchText = async (url: string): Promise<string> => {
    fetchedUrls.push(url);

    if (url.includes("geocoding.geo.census.gov")) {
      return JSON.stringify(geocoderPayload);
    }
    if (url.endsWith("/county-directory/")) {
      return countyIndexHtml;
    }
    if (url.endsWith("/county-directory/nueces.php")) {
      return countyPageHtml.replace(
        "http://www.ncadistrict.com/",
        "https://nuecescad.net/"
      );
    }
    if (url === "https://nuecescad.net/") {
      return `
        <html>
          <body>
            <a href="https://esearch.nuecescad.net/">Property Search</a>
          </body>
        </html>
      `;
    }
    if (url === "https://esearch.nuecescad.net/") {
      return `
        <html>
          <head>
            <meta name="search-token" content="token-value|2026-03-28T00:00:00Z" />
          </head>
          <body>
            Property Search
          </body>
        </html>
      `;
    }
    if (url.includes("/search/SearchResults?")) {
      return JSON.stringify({
        success: true,
        resultsList: [
          {
            propertyId: "14069438",
            ownerName: "Fiorini Family Trust",
            ownerId: "998877",
            address: "4141 Whiteley Dr, Corpus Christi, TX 78418",
            legalDescription: "LOT 4 BLOCK 3 EXAMPLE SUBDIVISION",
            appraisedValueDisplay: "$141,000",
            detailUrl: "/property/view/14069438?year=2026"
          }
        ]
      });
    }
    if (url === "https://esearch.nuecescad.net/property/view/14069438?year=2026") {
      return `
        <html>
          <body>
            <div class="property-summary">
              <div>Owner Name</div><div>Fiorini Family Trust</div>
              <div>Account Number</div><div>14069438</div>
              <div>Situs Address</div><div>4141 Whiteley Dr, Corpus Christi, TX 78418</div>
              <div>Legal Description</div><div>LOT 4 BLOCK 3 EXAMPLE SUBDIVISION</div>
              <div>Land Value</div><div>$42,000</div>
              <div>Improvement Value</div><div>$99,000</div>
              <div>Market Value</div><div>$141,000</div>
              <div>Assessed Value</div><div>$141,000</div>
              <div>Exemptions</div><div>Homestead</div>
            </div>
          </body>
        </html>
      `;
    }
    throw new Error(`Unexpected URL: ${url}`);
  };

  const payload = await resolvePublicRecords("4141 Whiteley Dr, Corpus Christi, TX 78418", {
    fetchText: enrichedFetchText
  });

  assert.equal(payload.propertyDetails?.propertyId, "14069438");
  assert.equal(payload.propertyDetails?.ownerName, "Fiorini Family Trust");
  assert.equal(payload.propertyDetails?.landValue, 42000);
  assert.equal(payload.propertyDetails?.improvementValue, 99000);
  assert.equal(payload.propertyDetails?.assessedTotalValue, 141000);
  assert.deepEqual(payload.propertyDetails?.exemptions, ["Homestead"]);
  assert.match(
    payload.lookupRecommendations.join(" "),
    /official cad property detail/i
  );
  assert.ok(
    fetchedUrls.some((url) => url.includes("esearch.nuecescad.net/property/view/14069438"))
  );
});

test("resolvePublicRecords uses formatted Nueces Geographic ID search when a parcel ID is available", async () => {
  const fetchedUrls: string[] = [];
  const enrichedFetchText = async (url: string): Promise<string> => {
    fetchedUrls.push(url);

    if (url.includes("geocoding.geo.census.gov")) {
      return JSON.stringify(geocoderPayload);
    }
    if (url.endsWith("/county-directory/")) {
      return countyIndexHtml;
    }
    if (url.endsWith("/county-directory/nueces.php")) {
      return countyPageHtml.replace(
        "http://www.ncadistrict.com/",
        "https://nuecescad.net/"
      );
    }
    if (url === "https://nuecescad.net/") {
      return `
        <html>
          <body>
            <a href="https://esearch.nuecescad.net/">Property Search</a>
          </body>
        </html>
      `;
    }
    if (url === "https://esearch.nuecescad.net/") {
      return `
        <html>
          <head>
            <meta name="search-token" content="token-value|2026-03-28T00:00:00Z" />
          </head>
          <body>
            Property Search
          </body>
        </html>
      `;
    }
    if (url.includes("/search/SearchResults?")) {
      assert.match(url, /keywords=1234-5678-9012/);
      return JSON.stringify({
        success: true,
        resultsList: [
          {
            propertyId: "200016970",
            ownerName: "NGUYEN TRANG THUY",
            ownerId: "677681",
            address: "6702 Everhart Rd Apt T106, Corpus Christi, TX 78413",
            legalDescription: "UNIT T106 EXAMPLE CONDO",
            appraisedValueDisplay: "$128,876",
            detailUrl: "/property/view/200016970?year=2026"
          }
        ]
      });
    }
    if (url === "https://esearch.nuecescad.net/property/view/200016970?year=2026") {
      return `
        <html>
          <body>
            <div class="property-summary">
              <div>Owner Name</div><div>NGUYEN TRANG THUY</div>
              <div>Account Number</div><div>200016970</div>
              <div>Situs Address</div><div>6702 Everhart Rd Apt T106, Corpus Christi, TX 78413</div>
              <div>Legal Description</div><div>UNIT T106 EXAMPLE CONDO</div>
              <div>Land Value</div><div>$20,000</div>
              <div>Improvement Value</div><div>$108,876</div>
              <div>Market Value</div><div>$128,876</div>
              <div>Assessed Value</div><div>$128,876</div>
            </div>
          </body>
        </html>
      `;
    }
    throw new Error(`Unexpected URL: ${url}`);
  };

  const payload = await resolvePublicRecords("6702 Everhart Rd APT T106, Corpus Christi, TX 78413", {
    parcelId: "123456789012",
    fetchText: enrichedFetchText
  });

  assert.equal(payload.propertyDetails?.propertyId, "200016970");
  assert.ok(
    fetchedUrls.some((url) => url.includes("keywords=1234-5678-9012"))
  );
});
