"""FD-1: canonical ForeignDevelopment storage/domain contract.

Every test runs against a throwaway foreign_offers.db under tmp_path. Both
DATA_DIR and storage_paths.REPO_ROOT are redirected (a real .env may set
DATA_DIR to the production-like InvestmentData directory), and the resolved
path is asserted to live under tmp_path before any test touches it.
"""
import sqlite3

import pytest

from modules.core import storage_paths

import InvestmentManager.foreign_offers_importer as importer
import InvestmentManager.foreign_offers_store as store


# Verbatim schema of foreign_offers.db before FD-1 (no foreign_developments,
# no foreign_offers.development_id) -- i.e. what production databases hold.
LEGACY_SCHEMA = """
CREATE TABLE foreign_offers (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    source_platform TEXT NOT NULL,
    source_url TEXT NOT NULL,
    source_offer_ref TEXT,
    source_country_code TEXT,
    source_country_name TEXT,
    source_region_name TEXT,
    source_city_name TEXT,
    source_location_text TEXT,
    source_market_type TEXT,
    offer_title TEXT,
    offer_description TEXT,
    price_value NUMERIC,
    price_currency TEXT,
    price_value_pln NUMERIC,
    area_total_m2 NUMERIC,
    area_living_m2 NUMERIC,
    plot_area_m2 NUMERIC,
    rooms_count INTEGER,
    bedrooms_count INTEGER,
    bathrooms_count INTEGER,
    floor INTEGER,
    floors_count INTEGER,
    construction_year INTEGER,
    latitude REAL,
    longitude REAL,
    map_place TEXT,
    map_accuracy TEXT,
    property_type_source TEXT,
    property_type_normalized TEXT,
    offer_type_normalized TEXT,
    market_type_normalized TEXT,
    category_id_domiporta TEXT,
    building_type_source TEXT,
    building_type_domiporta TEXT,
    plot_type_source TEXT,
    plot_type_domiporta TEXT,
    commercial_usage_source TEXT,
    commercial_usage_domiporta TEXT,
    sewerage_source TEXT,
    sewerage_domiporta TEXT,
    kitchen_source TEXT,
    kitchen_normalized TEXT,
    standard_source TEXT,
    standard_normalized TEXT,
    street_name TEXT,
    county_name TEXT,
    community_name TEXT,
    agent_identifier TEXT NOT NULL DEFAULT '101',
    agent_name TEXT,
    agent_email TEXT,
    agent_phone TEXT,
    is_active INTEGER NOT NULL DEFAULT 1,
    is_export_ready INTEGER NOT NULL DEFAULT 0,
    needs_update INTEGER NOT NULL DEFAULT 0,
    last_source_sync_at TEXT,
    last_source_change_at TEXT,
    last_exported_at TEXT,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(source_platform, source_url)
);
CREATE TABLE foreign_offer_images (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    foreign_offer_id INTEGER NOT NULL,
    image_url TEXT NOT NULL,
    sort_order INTEGER NOT NULL DEFAULT 0,
    is_primary INTEGER NOT NULL DEFAULT 0,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
);
CREATE TABLE foreign_offer_features_raw (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    foreign_offer_id INTEGER NOT NULL,
    feature_text TEXT NOT NULL,
    normalized_key TEXT,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
);
CREATE TABLE foreign_offer_raw_snapshots (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    foreign_offer_id INTEGER NOT NULL,
    payload_json TEXT NOT NULL,
    payload_hash TEXT NOT NULL,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
);
CREATE TABLE foreign_offer_sync_log (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    foreign_offer_id INTEGER NOT NULL,
    sync_status TEXT NOT NULL,
    change_detected INTEGER NOT NULL DEFAULT 0,
    summary TEXT,
    raw_hash_before TEXT,
    raw_hash_after TEXT,
    started_at TEXT,
    finished_at TEXT,
    FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
);
CREATE TABLE foreign_offer_export_warnings (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    foreign_offer_id INTEGER NOT NULL,
    warning_code TEXT NOT NULL,
    warning_message TEXT NOT NULL,
    field_name TEXT,
    is_blocking INTEGER NOT NULL DEFAULT 0,
    resolved_at TEXT,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
);
CREATE TABLE foreign_offer_portal_sync (
    foreign_offer_id INTEGER NOT NULL,
    portal_key TEXT NOT NULL,
    is_published INTEGER NOT NULL DEFAULT 0,
    needs_update INTEGER NOT NULL DEFAULT 0,
    last_action TEXT,
    last_filename TEXT,
    last_bytes INTEGER,
    last_error TEXT,
    last_uploaded_at TEXT,
    updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (foreign_offer_id, portal_key),
    FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
);
CREATE TABLE foreign_offer_portal_sync_events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    foreign_offer_id INTEGER NOT NULL,
    portal_key TEXT,
    event_type TEXT NOT NULL,
    payload_json TEXT,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
);
CREATE TRIGGER trg_foreign_offers_updated_at
AFTER UPDATE ON foreign_offers
FOR EACH ROW
BEGIN
    UPDATE foreign_offers
    SET updated_at = CURRENT_TIMESTAMP
    WHERE id = NEW.id;
END;
"""

# Columns the in-place migration appends to a legacy foreign_offers table.
MIGRATION_ADDED_COLUMNS = {
    "development_id", "floor_override", "area_net_m2", "area_gross_m2", "last_sync_run_id", "source_payload_hash",
    "source_values_json", "sync_run_id",
}

PORTAL_STATE_TABLES = (
    "foreign_offer_portal_sync",
    "foreign_offer_portal_sync_events",
    "foreign_offer_sync_log",
    "foreign_offer_raw_snapshots",
    "foreign_offer_export_warnings",
    "foreign_offer_images",
    "foreign_offer_features_raw",
    "sqlite_sequence",
)


@pytest.fixture()
def foreign_db(tmp_path, monkeypatch):
    monkeypatch.setenv(storage_paths.DATA_DIR_ENV_VAR, str(tmp_path))
    monkeypatch.setattr(storage_paths, "REPO_ROOT", tmp_path)
    db_path = storage_paths.foreign_offers_db_path()
    assert tmp_path in db_path.parents
    return db_path


def _raw_connect(db_path) -> sqlite3.Connection:
    db_path.parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(str(db_path))
    conn.row_factory = sqlite3.Row
    return conn


def _dump(conn: sqlite3.Connection, table: str) -> list[tuple]:
    # Compare only columns that existed before the additive migrations.
    columns = [row[1] for row in conn.execute(f"PRAGMA table_info({table})") if row[1] not in MIGRATION_ADDED_COLUMNS]
    return [tuple(row) for row in conn.execute(f"SELECT {', '.join(columns)} FROM {table} ORDER BY 1, 2")]


def _seed_published_offer(conn: sqlite3.Connection, offer_id: int, *, market: str = "primary") -> None:
    """Mirrors a real Domiporta-published offer, including portal/audit rows."""
    conn.execute(
        """
        INSERT INTO foreign_offers (
            id, source_platform, source_url, source_offer_ref, source_country_name,
            source_city_name, offer_title, price_value, price_currency, market_type_normalized,
            category_id_domiporta, is_export_ready, needs_update, last_exported_at,
            created_at, updated_at
        )
        VALUES (?, 'tripinvest', ?, ?, 'Spain', 'Orihuela Costa', ?, 350000, 'EUR', ?,
                '192', 1, 0, '2026-09-07 16:53:47', '2026-08-24 09:03:21', '2026-09-07 16:53:47')
        """,
        (
            offer_id,
            f"https://tripinvest.pl/oferta/offer-{offer_id}",
            str(70000 + offer_id),
            f"Willa {offer_id}",
            market,
        ),
    )
    conn.execute(
        """
        INSERT INTO foreign_offer_portal_sync (
            foreign_offer_id, portal_key, is_published, needs_update, last_action,
            last_filename, last_bytes, last_uploaded_at, updated_at
        )
        VALUES (?, 'domiporta', 1, 0, 'add', ?, 2205, '2026-09-07 16:53:47', '2026-09-07 16:53:47'),
               (?, 'tabelaofert', 0, 0, 'unpublished', NULL, NULL, NULL, '2026-08-24T09:03:21')
        """,
        (offer_id, f"domiporta_foreign_{offer_id}_20260907165343.zip", offer_id),
    )
    conn.execute(
        """
        INSERT INTO foreign_offer_portal_sync_events (foreign_offer_id, portal_key, event_type, payload_json, created_at)
        VALUES (?, 'domiporta', 'uploaded', '{"mode":"add"}', '2026-09-07 16:53:47')
        """,
        (offer_id,),
    )
    conn.execute(
        """
        INSERT INTO foreign_offer_sync_log (foreign_offer_id, sync_status, change_detected, summary, started_at)
        VALUES (?, 'success', 0, 'Tripinvest import completed', '2026-08-24 09:03:21')
        """,
        (offer_id,),
    )
    conn.execute(
        "INSERT INTO foreign_offer_raw_snapshots (foreign_offer_id, payload_json, payload_hash) VALUES (?, '{}', 'h')",
        (offer_id,),
    )
    conn.execute(
        """
        INSERT INTO foreign_offer_export_warnings (foreign_offer_id, warning_code, warning_message, field_name, is_blocking)
        VALUES (?, 'unmapped_features_present', 'msg', 'features', 0)
        """,
        (offer_id,),
    )
    conn.execute(
        "INSERT INTO foreign_offer_images (foreign_offer_id, image_url, sort_order, is_primary) VALUES (?, 'https://x/1.jpg', 0, 1)",
        (offer_id,),
    )
    conn.execute(
        "INSERT INTO foreign_offer_features_raw (foreign_offer_id, feature_text) VALUES (?, 'Basen')",
        (offer_id,),
    )


@pytest.fixture()
def legacy_db(foreign_db):
    """Pre-FD-1 database holding published offers with a gapped AUTOINCREMENT."""
    conn = _raw_connect(foreign_db)
    conn.executescript(LEGACY_SCHEMA)
    for offer_id in (1, 5, 6, 8):
        _seed_published_offer(conn, offer_id)
    conn.execute("UPDATE sqlite_sequence SET seq = 8 WHERE name = 'foreign_offers'")
    conn.commit()
    conn.close()
    return foreign_db


@pytest.fixture()
def fresh_db(foreign_db):
    store.initialize_foreign_offers_db()
    return foreign_db


def _snapshot_all(db_path) -> dict:
    conn = _raw_connect(db_path)
    try:
        legacy_offer_columns = [
            row[1] for row in conn.execute("PRAGMA table_info(foreign_offers)")
            if row[1] not in MIGRATION_ADDED_COLUMNS
        ]
        state = {
            "foreign_offers": [
                tuple(row)
                for row in conn.execute(f"SELECT {', '.join(legacy_offer_columns)} FROM foreign_offers ORDER BY id")
            ]
        }
        for table in PORTAL_STATE_TABLES:
            state[table] = _dump(conn, table)
        return state
    finally:
        conn.close()


# ---------------------------------------------------------------------------
# A/B. Migration of an existing (pre-FD-1) database
# ---------------------------------------------------------------------------


def test_legacy_database_migrates_in_place_idempotently(legacy_db):
    before = _snapshot_all(legacy_db)

    store.initialize_foreign_offers_db()
    store.initialize_foreign_offers_db()

    conn = _raw_connect(legacy_db)
    try:
        tables = {row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type = 'table'")}
        assert "foreign_developments" in tables
        columns = {row[1]: row for row in conn.execute("PRAGMA table_info(foreign_offers)")}
        assert "development_id" in columns
        assert columns["development_id"][3] == 0  # nullable
        indexes = {row[1] for row in conn.execute("PRAGMA index_list(foreign_offers)")}
        assert "idx_foreign_offers_development_id" in indexes
        fks = [tuple(row)[2:5] for row in conn.execute("PRAGMA foreign_key_list(foreign_offers)")]
        assert ("foreign_developments", "development_id", "id") in fks
        assert [row[0] for row in conn.execute("SELECT id FROM foreign_offers ORDER BY id")] == [1, 5, 6, 8]
        assert {row[0] for row in conn.execute("SELECT development_id FROM foreign_offers")} == {None}
    finally:
        conn.close()

    from tests.investmentmanager.foreign_revision_assertions import assert_guard_install_only
    assert_guard_install_only(before,_snapshot_all(legacy_db))


def test_legacy_migration_preserves_domiporta_state_and_sequence(legacy_db):
    before = _snapshot_all(legacy_db)

    store.initialize_foreign_offers_db()

    after = _snapshot_all(legacy_db)
    assert after["foreign_offer_portal_sync"] == before["foreign_offer_portal_sync"]
    from tests.investmentmanager.foreign_revision_assertions import assert_guard_install_only
    assert_guard_install_only(before,after)
    assert ("foreign_offers", 8) in after["sqlite_sequence"]

    conn = _raw_connect(legacy_db)
    try:
        published = conn.execute(
            """
            SELECT foreign_offer_id, is_published, last_filename
            FROM foreign_offer_portal_sync
            WHERE portal_key = 'domiporta'
            ORDER BY foreign_offer_id
            """
        ).fetchall()
        assert [tuple(row) for row in published] == [
            (offer_id, 1, f"domiporta_foreign_{offer_id}_20260907165343.zip") for offer_id in (1, 5, 6, 8)
        ]
    finally:
        conn.close()


def test_new_offer_after_migration_does_not_reuse_deleted_offer_ids(legacy_db):
    store.initialize_foreign_offers_db()
    conn = _raw_connect(legacy_db)
    try:
        cursor = conn.execute(
            "INSERT INTO foreign_offers (source_platform, source_url) VALUES ('tripinvest', 'https://tripinvest.pl/oferta/new')"
        )
        assert cursor.lastrowid == 9
    finally:
        conn.close()


def test_migration_tolerates_concurrent_duplicate_column(legacy_db, monkeypatch):
    """Another initializer adds the column between our check and our ALTER."""
    conn = store.open_foreign_offers_connection()
    try:
        store.ensure_foreign_offers_schema(conn)
        real_execute = conn.execute

        class StaleTableInfoConnection:
            def execute(self, sql, *args):
                if sql.startswith("PRAGMA table_info"):
                    return iter([(0, "id")])
                return real_execute(sql, *args)

        store._ensure_foreign_offers_development_column(StaleTableInfoConnection())
    finally:
        conn.close()


def test_migration_does_not_swallow_unrelated_errors():
    class BrokenConnection:
        def execute(self, sql, *args):
            if sql.startswith("PRAGMA table_info"):
                return iter([(0, "id")])
            raise sqlite3.OperationalError("database is locked")

    with pytest.raises(sqlite3.OperationalError, match="locked"):
        store._ensure_foreign_offers_development_column(BrokenConnection())


# ---------------------------------------------------------------------------
# C/D/E. ForeignDevelopment entity
# ---------------------------------------------------------------------------


def test_create_development_returns_stored_values(fresh_db):
    created = store.create_foreign_development("  Azure   Bay ")

    assert isinstance(created["id"], int)
    assert created["name"] == "Azure Bay"
    assert created["created_at"] and created["updated_at"]
    assert store.list_foreign_developments() == [created]


@pytest.mark.parametrize("name", ["", "   ", None])
def test_create_development_requires_name(fresh_db, name):
    with pytest.raises(ValueError):
        store.create_foreign_development(name)


@pytest.mark.parametrize("duplicate", ["Azure Bay", "azure bay", "AZURE BAY", "  azure  BAY "])
def test_development_name_is_case_insensitively_unique(fresh_db, duplicate):
    store.create_foreign_development("Azure Bay")

    with pytest.raises(sqlite3.IntegrityError):
        store.create_foreign_development(duplicate)

    assert [d["name"] for d in store.list_foreign_developments()] == ["Azure Bay"]


def test_rename_preserves_id_and_updates_updated_at(fresh_db):
    created = store.create_foreign_development("Azure Bay")
    conn = _raw_connect(fresh_db)
    conn.execute(
        "UPDATE foreign_developments SET created_at = '2000-01-01 00:00:00', updated_at = '2000-01-01 00:00:00'"
    )
    conn.commit()
    conn.close()

    renamed = store.rename_foreign_development(created["id"], "Azure Bay Residences")

    assert renamed["id"] == created["id"]
    assert renamed["name"] == "Azure Bay Residences"
    assert renamed["created_at"] == "2000-01-01 00:00:00"
    assert renamed["updated_at"] != "2000-01-01 00:00:00"


def test_rename_rejects_taken_name_and_reports_missing_development(fresh_db):
    store.create_foreign_development("Azure Bay")
    other = store.create_foreign_development("Sol Park")

    with pytest.raises(sqlite3.IntegrityError):
        store.rename_foreign_development(other["id"], "AZURE BAY")
    assert store.rename_foreign_development(9999, "Anything") is None


def test_deleted_development_id_is_never_reused(fresh_db):
    first = store.create_foreign_development("Azure Bay")
    assert store.delete_foreign_development(first["id"]) is True

    second = store.create_foreign_development("Sol Park")

    assert second["id"] > first["id"]
    assert store.delete_foreign_development(first["id"]) is False


# ---------------------------------------------------------------------------
# F/G/H/I. Assignment semantics and FK safety
# ---------------------------------------------------------------------------


def _list_item(offer_id: int) -> dict:
    return next(item for item in store.list_foreign_offers() if item["id"] == offer_id)


@pytest.fixture()
def seeded_fresh_db(fresh_db):
    conn = _raw_connect(fresh_db)
    _seed_published_offer(conn, 1)
    _seed_published_offer(conn, 2, market="secondary")
    conn.commit()
    conn.close()
    return fresh_db


def test_assign_reassign_and_unassign(seeded_fresh_db):
    azure = store.create_foreign_development("Azure Bay")
    sol = store.create_foreign_development("Sol Park")

    assigned = store.set_foreign_offer_development(1, azure["id"])
    assert assigned == {"foreign_offer_id": 1, "development_id": azure["id"], "development_name": "Azure Bay"}
    assert (_list_item(1)["development_id"], _list_item(1)["development_name"]) == (azure["id"], "Azure Bay")

    store.set_foreign_offer_development(1, sol["id"])
    assert (_list_item(1)["development_id"], _list_item(1)["development_name"]) == (sol["id"], "Sol Park")

    unassigned = store.set_foreign_offer_development(1, None)
    assert unassigned == {"foreign_offer_id": 1, "development_id": None, "development_name": None}
    assert (_list_item(1)["development_id"], _list_item(1)["development_name"]) == (None, None)


def test_secondary_offer_may_be_assigned_no_market_restriction(seeded_fresh_db):
    azure = store.create_foreign_development("Azure Bay")
    assert store.set_foreign_offer_development(2, azure["id"])["development_id"] == azure["id"]


def test_assignment_to_missing_offer_returns_none(seeded_fresh_db):
    azure = store.create_foreign_development("Azure Bay")
    assert store.set_foreign_offer_development(999, azure["id"]) is None


def test_fk_rejects_unknown_development_and_blocks_referenced_delete(seeded_fresh_db):
    azure = store.create_foreign_development("Azure Bay")
    unused = store.create_foreign_development("Sol Park")

    with pytest.raises(sqlite3.IntegrityError):
        store.set_foreign_offer_development(1, 424242)
    assert _list_item(1)["development_id"] is None

    store.set_foreign_offer_development(1, azure["id"])
    with pytest.raises(sqlite3.IntegrityError):
        store.delete_foreign_development(azure["id"])
    assert _list_item(1)["development_id"] == azure["id"]
    assert len(store.list_foreign_offers()) == 2

    assert store.delete_foreign_development(unused["id"]) is True
    assert [d["name"] for d in store.list_foreign_developments()] == ["Azure Bay"]


# ---------------------------------------------------------------------------
# J. Importer preserves the CRM-owned assignment
# ---------------------------------------------------------------------------


class _FakeTripinvestConnector:
    title = "Willa przed odświeżeniem"

    def fetch_offer(self, identifier):
        return {"kind": "offer_details", "offer": {}, "url": identifier["url"]}

    def normalize_offer(self, raw_offer):
        return {
            "source": {"external_id": "73567"},
            "listing": {
                "title": type(self).title,
                "description_text": "Opis",
                "property_type": "dom",
                "offer_type": "sale",
                "market_type": "pierwotny",
                "location": {"address_label": "Costa Blanca, Orihuela Costa"},
            },
            "pricing": {"amount": 350000, "currency": "EUR"},
            "metrics": {"area_m2": 126, "bedrooms": 3, "bathrooms": 2},
            "media": {"gallery": ["https://static.example/1.jpg"]},
            "raw": {"payload": {"title": type(self).title, "map": {}, "features": []}},
        }


def test_source_refresh_preserves_manual_development_assignment(fresh_db, monkeypatch):
    monkeypatch.setattr(importer, "TripinvestConnector", _FakeTripinvestConnector)
    url = "https://tripinvest.pl/oferta/zjawiskowa-willa-73567"

    first = importer.upsert_foreign_offer_from_tripinvest(url)
    offer_id = first["foreign_offer_id"]
    azure = store.create_foreign_development("Azure Bay")
    store.set_foreign_offer_development(offer_id, azure["id"])

    monkeypatch.setattr(_FakeTripinvestConnector, "title", "Willa po odświeżeniu")
    second = importer.upsert_foreign_offer_from_tripinvest(url)

    item = _list_item(offer_id)
    assert second["foreign_offer_id"] == offer_id
    assert item["offer_title"] == "Willa po odświeżeniu"
    assert item["market_type_normalized"] == "primary"
    assert (item["development_id"], item["development_name"]) == (azure["id"], "Azure Bay")


# ---------------------------------------------------------------------------
# K. List contract
# ---------------------------------------------------------------------------

PRE_FD1_LIST_KEYS = {
    "id", "source_platform", "source_url", "source_offer_ref", "offer_title", "source_country_name",
    "source_region_name", "source_city_name", "source_location_text", "source_market_type", "price_value",
    "price_currency", "area_total_m2", "rooms_count", "bedrooms_count", "bathrooms_count", "offer_description",
    "property_type_source", "offer_type_normalized", "market_type_normalized", "map_place", "map_accuracy",
    "latitude", "longitude", "category_id_domiporta", "is_export_ready", "needs_update", "last_source_sync_at",
    "last_source_change_at", "created_at", "warning_count", "blocking_warning_count", "warnings", "images",
    "features", "portal_sync",
}


def test_list_contract_keeps_existing_keys_and_adds_development(seeded_fresh_db):
    azure = store.create_foreign_development("Azure Bay")
    store.set_foreign_offer_development(1, azure["id"])

    items = {item["id"]: item for item in store.list_foreign_offers()}

    for item in items.values():
        assert PRE_FD1_LIST_KEYS <= set(item)
    assert (items[1]["development_id"], items[1]["development_name"]) == (azure["id"], "Azure Bay")
    assert (items[2]["development_id"], items[2]["development_name"]) == (None, None)
    assert items[1]["portal_sync"]["domiporta"]["is_published"] == 1
    assert len(items[1]["images"]) == 1
    assert len(items[1]["features"]) == 1
    assert "unmapped_features_present" in {w["warning_code"] for w in items[1]["warnings"]}  # legacy row kept


def test_list_works_on_migrated_legacy_database(legacy_db):
    items = store.list_foreign_offers()
    assert [item["id"] for item in items] == [8, 6, 5, 1]
    assert all(item["development_id"] is None and item["development_name"] is None for item in items)


# ---------------------------------------------------------------------------
# L. Domiporta / portal state isolation
# ---------------------------------------------------------------------------


def test_development_changes_keep_publication_state_and_export_timestamps(seeded_fresh_db):
    # An actual change now also recomputes warnings and flags a published offer
    # (needs_update, event); what must stay untouched is the publication state
    # itself, the export timestamp and the legacy warning rows.
    azure = store.create_foreign_development("Azure Bay")
    sol = store.create_foreign_development("Sol Park")

    def export_state():
        conn = _raw_connect(seeded_fresh_db)
        try:
            offers = [
                tuple(row)
                for row in conn.execute("SELECT id, last_exported_at FROM foreign_offers ORDER BY id")
            ]
            portal = [
                tuple(row)
                for row in conn.execute(
                    "SELECT foreign_offer_id, portal_key, is_published, last_action, last_filename, last_bytes, "
                    "last_uploaded_at FROM foreign_offer_portal_sync ORDER BY 1, 2"
                )
            ]
            legacy_warnings = [
                tuple(row)
                for row in conn.execute(
                    "SELECT foreign_offer_id, warning_code, is_blocking FROM foreign_offer_export_warnings "
                    "WHERE warning_code = 'unmapped_features_present' ORDER BY id"
                )
            ]
            return offers, portal, legacy_warnings
        finally:
            conn.close()

    before = export_state()
    for development_id in (azure["id"], sol["id"], None):
        store.set_foreign_offer_development(1, development_id)
        assert export_state() == before
    store.rename_foreign_development(sol["id"], "Sol Park II")
    assert export_state() == before
