/**
 * Tests for `adaptEgrn` — issue #1217 (P2 prod-bug).
 *
 * Bug: frontend cast `data.egrn as ParcelEgrn` without mapping; backend
 * `egrn_block` ships ЕГРН column names (`permitted_use_text`, `land_category`,
 * `ownership_type`, `parcel_status`, `last_egrn_update_date`) but the frontend
 * type expects the labelled form (`vri`, `category`, `owner_type`, `status`,
 * `last_updated`). 6/10 rows of the ЕГРН table and the matching CSV cells
 * rendered empty in prod. The dev mock fixture hid the bug by storing the old
 * frontend shape; it's been rewritten alongside this adapter to the real shape.
 *
 * Fix: `adaptEgrn(raw, cad)` maps backend → frontend; an empty `{}` returns
 * `null` so the caller falls back to `buildFallbackEgrn(cad)`.
 */
import { describe, expect, it } from "vitest";

import { adaptEgrn } from "../site-finder-api";

const CAD = "66:41:0701045:42";

describe("adaptEgrn — backend egrn_block → frontend ParcelEgrn (#1217)", () => {
  it("maps the real backend egrn_block shape into ParcelEgrn", () => {
    // Mirror of backend/app/api/v1/parcels.py:2004-2024 (egrn_block).
    const backend = {
      cadastral_value_rub: 12_500_000,
      cadastral_value_per_m2: 1_517.0,
      land_category: "Земли населённых пунктов",
      permitted_use_text: "Многоэтажная жилая застройка (МКД)",
      last_egrn_update_date: "2025-10-01",
      area_m2: 8240,
      ownership_type: "Государственная",
      right_type: "Постоянное (бессрочное) пользование",
      parcel_status: "Учтённый",
      address: "Свердловская обл., г. Екатеринбург, ул. Ленина, 42",
      registration_date: "2003-07-15",
    };

    const adapted = adaptEgrn(backend, CAD);

    expect(adapted).not.toBeNull();
    expect(adapted).toEqual({
      cad_num: CAD,
      address: "Свердловская обл., г. Екатеринбург, ул. Ленина, 42",
      area_m2: 8240,
      vri: "Многоэтажная жилая застройка (МКД)",
      category: "Земли населённых пунктов",
      registration_date: "2003-07-15",
      owner_type: "Государственная",
      // encumbrance lives in a sibling encumbrance_block, not egrn_block.
      encumbrance: "—",
      status: "Учтённый",
      last_updated: "2025-10-01",
    });
  });

  it("returns null for an empty object (backend writes {} on missing row)", () => {
    expect(adaptEgrn({}, CAD)).toBeNull();
  });

  it("returns null for null / undefined / non-object input", () => {
    expect(adaptEgrn(null, CAD)).toBeNull();
    expect(adaptEgrn(undefined, CAD)).toBeNull();
    expect(adaptEgrn("not-an-object", CAD)).toBeNull();
    expect(adaptEgrn(42, CAD)).toBeNull();
  });

  it("defaults missing string fields to em-dash, missing area to NaN", () => {
    // Partial backend response (some columns NULL in cad_parcels).
    const partial = {
      address: null,
      area_m2: null,
      permitted_use_text: null,
      land_category: null,
      ownership_type: null,
      parcel_status: null,
      last_egrn_update_date: null,
      registration_date: null,
      // Presence guarantees the object isn't empty so we adapt rather than
      // returning null (caller's fallback is for a totally missing block).
    };

    const adapted = adaptEgrn(partial, CAD);

    expect(adapted).not.toBeNull();
    expect(adapted?.cad_num).toBe(CAD);
    expect(adapted?.address).toBe("—");
    expect(adapted?.vri).toBe("—");
    expect(adapted?.category).toBe("—");
    expect(adapted?.owner_type).toBe("—");
    expect(adapted?.status).toBe("—");
    expect(adapted?.encumbrance).toBe("—");
    expect(adapted?.registration_date).toBeNull();
    expect(adapted?.last_updated).toBeNull();
    expect(Number.isNaN(adapted?.area_m2)).toBe(true);
  });

  it("threads `cad` through (egrn_block has no cad_num column)", () => {
    const adapted = adaptEgrn(
      { address: "ул. Тестовая, 1", permitted_use_text: "test" },
      "66:00:1234567:89",
    );
    expect(adapted?.cad_num).toBe("66:00:1234567:89");
  });

  it("ignores empty strings the same as missing values", () => {
    const adapted = adaptEgrn(
      {
        address: "",
        permitted_use_text: "",
        land_category: "Земли населённых пунктов",
      },
      CAD,
    );
    expect(adapted?.address).toBe("—");
    expect(adapted?.vri).toBe("—");
    expect(adapted?.category).toBe("Земли населённых пунктов");
  });

  it("rejects non-finite area_m2 (Infinity / NaN from backend)", () => {
    const adapted = adaptEgrn(
      { area_m2: Number.POSITIVE_INFINITY, address: "x" },
      CAD,
    );
    expect(Number.isNaN(adapted?.area_m2)).toBe(true);
  });
});
