"""Test-only schemas and row builder copied from IDBManager b820d18."""
import sqlite3

OLD_FOREIGN_OFFERS_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)
);
"""

NEW_SCHEMA_MIGRATIONS = """
CREATE TABLE foreign_developments (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL COLLATE NOCASE UNIQUE,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE foreign_offers ADD COLUMN development_id INTEGER;
ALTER TABLE foreign_offers ADD COLUMN floor_override INTEGER;
"""

def _offer_row(schema: str, **values) -> sqlite3.Row:
    conn = sqlite3.connect(":memory:")
    conn.row_factory = sqlite3.Row
    conn.executescript(OLD_FOREIGN_OFFERS_SCHEMA)
    if schema == "new":
        conn.executescript(NEW_SCHEMA_MIGRATIONS)
    development_name = values.pop("development_name", None)
    missing_development = bool(values.pop("missing_development", False))
    row = {
        "id": 8,
        "source_platform": "tripinvest",
        "source_url": "https://tripinvest.pl/oferta/apartament-75136",
        "offer_title": "Apartament",
        "offer_description": "Opis oferty",
        "source_country_name": "Hiszpania",
        "source_region_name": "Costa Blanca",
        "source_city_name": "Torrevieja",
        "source_location_text": "Costa Blanca, Torrevieja",
        "latitude": 37.98,
        "longitude": -0.71,
        "area_total_m2": 104,
        "plot_area_m2": 120,
        "rooms_count": 4,
        "bedrooms_count": 3,
        "bathrooms_count": 2,
        "price_value": 250000,
        "price_currency": "EUR",
        "offer_type_normalized": "sale",
        "market_type_normalized": "primary",
        "category_id_domiporta": "191",
        "property_type_source": "apartament",
    }
    row.update(values)
    if schema == "new" and development_name is not None and row.get("development_id") is not None and not missing_development:
        conn.execute(
            "INSERT INTO foreign_developments (id, name) VALUES (?, ?)",
            (int(row["development_id"]), development_name),
        )
    columns = ", ".join(row)
    placeholders = ", ".join("?" for _ in row)
    conn.execute(f"INSERT INTO foreign_offers ({columns}) VALUES ({placeholders})", tuple(row.values()))
    if schema == "new":
        return conn.execute(
            """
            SELECT fo.*, fd.name AS development_name
            FROM foreign_offers fo
            LEFT JOIN foreign_developments fd ON fd.id = fo.development_id
            WHERE fo.id = ?
            """,
            (row["id"],),
        ).fetchone()
    return conn.execute("SELECT * FROM foreign_offers WHERE id = ?", (row["id"],)).fetchone()

FOREIGN_OFFER_SIDE_TABLES = """
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
);
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
);
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
);
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)
);
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
);
"""
