import { db } from "~/server/db";
import { propertyWatchlistItems } from "~/server/db/schema";
import type { SnapshotData } from "./change.detector";

export interface CountyRecord extends SnapshotData {
  address: Record<string, string>;
  deedDate: string | null;
  taxId: string | null;
}

export async function fetchCountyRecords(
  parcelId: string | null,
  _county: string,
  _state: string,
): Promise<CountyRecord | null> {
  console.log(`[hometitle] fetchCountyRecords called for parcelId=${parcelId}`);

  if (!parcelId) {
    return null;
  }

  return {
    ownerName: "Unknown Owner",
    address: { street: "", city: "", state: "", zip: "" },
    deedDate: null,
    taxId: null,
    propertyType: "residential",
    taxAmount: null,
    lienCount: 0,
  };
}

export function parseDeedRecords(_html: string): CountyRecord | null {
  console.log("[hometitle] parseDeedRecords called - not yet implemented for HTML parsing");
  return null;
}

export async function geocodeAddress(
  address: string,
): Promise<{ latitude: number; longitude: number } | null> {
  console.log(`[hometitle] geocodeAddress called for address=${address}`);

  if (!process.env.GEOCODING_API_KEY) {
    return null;
  }

  try {
    const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=${process.env.GEOCODING_API_KEY}`;
    const res = await fetch(url);
    const data = await res.json() as { results?: Array<{ geometry: { location: { lat: number; lng: number } } }>; status: string };

    if (data.status === "OK" && data.results?.[0]?.geometry?.location) {
      const { lat, lng } = data.results[0].geometry.location;
      return { latitude: lat, longitude: lng };
    }

    console.warn(`[hometitle] Geocoding failed for address: ${address}, status: ${data.status}`);
    return null;
  } catch (err) {
    console.error("[hometitle] Geocoding error:", err);
    return null;
  }
}

export async function getLastSnapshot(propertyWatchlistItemId: string) {
  const { propertySnapshots } = await import("~/server/db/schema");
  const { desc, eq, and } = await import("drizzle-orm");

  const [snapshot] = await db
    .select()
    .from(propertySnapshots)
    .where(eq(propertySnapshots.propertyWatchlistItemId, propertyWatchlistItemId))
    .orderBy(desc(propertySnapshots.capturedAt))
    .limit(1);

  return snapshot ?? null;
}

export function parseAddress(address: string): { streetAddress: string; city: string; state: string; zipCode: string } {
  const parts = address.split(",").map((p) => p.trim());
  const streetAddress = parts[0] ?? "";
  let city = "";
  let state = "";
  let zipCode = "";

  if (parts.length >= 2) {
    const lastPart = parts[parts.length - 1] ?? "";
    const stateZip = lastPart.split(" ").filter(Boolean);
    if (stateZip.length >= 2) {
      state = stateZip[0] ?? "";
      zipCode = stateZip[stateZip.length - 1] ?? "";
    }
    if (parts.length >= 3) {
      city = parts[parts.length - 2] ?? "";
    }
  }

  return { streetAddress, city, state, zipCode };
}
