"""FD-2: ForeignDevelopment CRM routes on the existing foreign-offers panel.

Runs the real create_app() blueprint against a throwaway foreign_offers.db:
DATA_DIR and storage_paths.REPO_ROOT both point at tmp_path (a real .env may
set DATA_DIR to InvestmentData), asserted before any request is made.
"""
import sqlite3

import pytest

from modules.core import storage_paths

import InvestmentManager.foreign_offers_store as store
import InvestmentManager.routes.foreign_offers as foreign_offer_routes

ADMIN_LEVELS = ("master", "admin")


@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
    store.initialize_foreign_offers_db()
    conn = _raw_connect(db_path)
    for offer_id, market in ((1, "primary"), (5, "secondary")):
        _seed_published_offer(conn, offer_id, market)
    conn.commit()
    conn.close()
    return db_path


def _raw_connect(db_path) -> sqlite3.Connection:
    conn = sqlite3.connect(str(db_path))
    conn.row_factory = sqlite3.Row
    return conn


def _seed_published_offer(conn, offer_id: int, market: str) -> None:
    conn.execute(
        """
        INSERT INTO foreign_offers (
            id, source_platform, source_url, offer_title, market_type_normalized,
            category_id_domiporta, is_export_ready, needs_update, last_exported_at
        )
        VALUES (?, 'tripinvest', ?, ?, ?, '192', 1, 0, '2026-09-07 16:53:47')
        """,
        (offer_id, f"https://tripinvest.pl/oferta/offer-{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')
        """,
        (offer_id, f"domiporta_foreign_{offer_id}_20260907165343.zip"),
    )
    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,),
    )


def _login(client, access_level="master"):
    with client.session_transaction() as sess:
        sess["user_id"] = 1
        sess["access_level"] = access_level
        sess["first_name"] = "Test"
        sess["last_name"] = "Admin"


@pytest.fixture()
def admin(client, foreign_db):
    _login(client)
    return client


def _create(client, name):
    return client.post("/crm/foreign-offers/developments", json={"name": name})


def _assign(client, offer_id, development_id):
    return client.post(f"/crm/foreign-offers/{offer_id}/development", json={"development_id": development_id})


def _offer(client, offer_id):
    items = client.get("/crm/foreign-offers/list").get_json()["items"]
    return next(item for item in items if item["id"] == offer_id)


def _db_state(db_path):
    conn = _raw_connect(db_path)
    try:
        return {
            "offers": [tuple(r) for r in conn.execute(
                "SELECT id, development_id, needs_update, last_exported_at, is_export_ready FROM foreign_offers ORDER BY id"
            )],
            "developments": [tuple(r) for r in conn.execute("SELECT id, name FROM foreign_developments ORDER BY id")],
            "portal_sync": [tuple(r) for r in conn.execute("SELECT * FROM foreign_offer_portal_sync ORDER BY 1, 2")],
            "events": [tuple(r) for r in conn.execute("SELECT * FROM foreign_offer_portal_sync_events ORDER BY id")],
        }
    finally:
        conn.close()


# ---------------------------------------------------------------------------
# LIST
# ---------------------------------------------------------------------------


def test_list_includes_developments_and_development_fields(admin):
    created = _create(admin, "Azure Bay").get_json()["item"]
    _create(admin, "Sol Park")
    assert _assign(admin, 1, created["id"]).status_code == 200

    payload = admin.get("/crm/foreign-offers/list").get_json()

    assert payload["developments"] == [
        {"id": created["id"], "name": "Azure Bay"},
        {"id": created["id"] + 1, "name": "Sol Park"},
    ]
    items = {item["id"]: item for item in payload["items"]}
    assert set(items) == {1, 5}
    assert (items[1]["development_id"], items[1]["development_name"]) == (created["id"], "Azure Bay")
    assert (items[5]["development_id"], items[5]["development_name"]) == (None, None)
    assert items[1]["portal_sync"]["domiporta"]["is_published"] == 1
    assert items[1]["offer_title"] == "Willa 1"
    assert items[1]["market_type_normalized"] == "primary"


def test_list_developments_empty_by_default(admin):
    payload = admin.get("/crm/foreign-offers/list").get_json()
    assert payload["developments"] == []
    assert len(payload["items"]) == 2


# ---------------------------------------------------------------------------
# CREATE
# ---------------------------------------------------------------------------


def test_create_development(admin):
    response = _create(admin, "  Azure   Bay ")

    assert response.status_code == 200
    body = response.get_json()
    assert body["ok"] is True
    assert body["item"]["name"] == "Azure Bay"
    assert isinstance(body["item"]["id"], int)


@pytest.mark.parametrize("payload", [
    {"name": ""},
    {"name": "   "},
    {},
    {"name": None},
    {"name": 123},
    {"name": ["Azure Bay"]},
    {"name": {"value": "Azure Bay"}},
    ["Azure Bay"],
    "Azure Bay",
])
def test_create_development_rejects_invalid_payload(admin, foreign_db, payload):
    before = _db_state(foreign_db)
    response = admin.post("/crm/foreign-offers/developments", json=payload)
    assert response.status_code == 400
    assert _db_state(foreign_db) == before


def test_create_development_rejects_non_json_body(admin):
    response = admin.post("/crm/foreign-offers/developments", data="name=Azure", content_type="text/plain")
    assert response.status_code == 400


@pytest.mark.parametrize("duplicate", ["Azure Bay", "azure bay", "AZURE BAY", " Azure  Bay "])
def test_create_duplicate_development_returns_409(admin, duplicate):
    assert _create(admin, "Azure Bay").status_code == 200
    response = _create(admin, duplicate)
    assert response.status_code == 409
    assert response.get_json()["error"]


# ---------------------------------------------------------------------------
# RENAME
# ---------------------------------------------------------------------------


def test_rename_development_keeps_id_and_updates_assigned_offers(admin):
    created = _create(admin, "Azure Bay").get_json()["item"]
    _assign(admin, 1, created["id"])

    response = admin.post(f"/crm/foreign-offers/developments/{created['id']}", json={"name": "Azure Bay Residence"})

    assert response.status_code == 200
    assert response.get_json()["item"]["id"] == created["id"]
    assert response.get_json()["item"]["name"] == "Azure Bay Residence"
    assert (_offer(admin, 1)["development_id"], _offer(admin, 1)["development_name"]) == (
        created["id"],
        "Azure Bay Residence",
    )


@pytest.mark.parametrize("development_id", [9999, 2**63])
def test_rename_missing_development_returns_404(admin, development_id):
    response = admin.post(f"/crm/foreign-offers/developments/{development_id}", json={"name": "Nowa"})
    assert response.status_code == 404


@pytest.mark.parametrize("payload", [{"name": ""}, {"name": "  "}, {}, {"name": 5}, None])
def test_rename_rejects_invalid_name(admin, payload):
    created = _create(admin, "Azure Bay").get_json()["item"]
    response = admin.post(f"/crm/foreign-offers/developments/{created['id']}", json=payload)
    assert response.status_code == 400


def test_rename_to_taken_name_returns_409(admin):
    _create(admin, "Azure Bay")
    other = _create(admin, "Sol Park").get_json()["item"]
    response = admin.post(f"/crm/foreign-offers/developments/{other['id']}", json={"name": "azure BAY"})
    assert response.status_code == 409


# ---------------------------------------------------------------------------
# ASSIGN / REASSIGN / UNASSIGN
# ---------------------------------------------------------------------------


def test_assign_reassign_unassign(admin):
    azure = _create(admin, "Azure Bay").get_json()["item"]
    sol = _create(admin, "Sol Park").get_json()["item"]

    response = _assign(admin, 1, azure["id"])
    assert response.status_code == 200
    assert response.get_json() == {
        "ok": True,
        "item": {"foreign_offer_id": 1, "development_id": azure["id"], "development_name": "Azure Bay"},
    }

    response = _assign(admin, 1, sol["id"])
    assert response.get_json()["item"]["development_name"] == "Sol Park"
    assert _offer(admin, 1)["development_id"] == sol["id"]

    response = _assign(admin, 1, None)
    assert response.status_code == 200
    assert response.get_json()["item"] == {"foreign_offer_id": 1, "development_id": None, "development_name": None}
    assert _offer(admin, 1)["development_id"] is None


@pytest.mark.parametrize("offer_id", [999, 2**63])
def test_assign_to_missing_offer_returns_404(admin, offer_id):
    azure = _create(admin, "Azure Bay").get_json()["item"]
    assert _assign(admin, offer_id, azure["id"]).status_code == 404


def test_assign_unknown_development_returns_400(admin, foreign_db):
    before = _db_state(foreign_db)
    response = _assign(admin, 1, 424242)
    assert response.status_code == 400
    assert _db_state(foreign_db) == before


@pytest.mark.parametrize("payload", [{}, None, [], "5", {"development": 1}])
def test_assign_requires_explicit_development_id(admin, payload):
    response = admin.post("/crm/foreign-offers/1/development", json=payload)
    assert response.status_code == 400


# ---------------------------------------------------------------------------
# TYPE VALIDATION
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("value", ["5", True, False, 5.0, {}, [], 0, -1, 2**63])
def test_assign_rejects_non_integer_development_id(admin, foreign_db, value):
    # Developments 1 and 5 exist, so int() coercion of True / "5" / 5.0 would
    # succeed: a 400 here proves the route's type check, not the FK.
    conn = _raw_connect(foreign_db)
    conn.execute("INSERT INTO foreign_developments (id, name) VALUES (1, 'One'), (5, 'Five')")
    conn.commit()
    conn.close()
    before = _db_state(foreign_db)

    response = _assign(admin, 1, value)

    assert response.status_code == 400
    assert _db_state(foreign_db) == before


@pytest.mark.parametrize("value, expected", [(5, 5), (None, None)])
def test_assign_accepts_integer_or_null(admin, foreign_db, value, expected):
    conn = _raw_connect(foreign_db)
    conn.execute("INSERT INTO foreign_developments (id, name) VALUES (5, 'Five')")
    conn.commit()
    conn.close()

    response = _assign(admin, 1, value)

    assert response.status_code == 200
    assert response.get_json()["item"]["development_id"] == expected


# ---------------------------------------------------------------------------
# ERROR MAPPING: unexpected database errors are not disguised
# ---------------------------------------------------------------------------


def test_unexpected_integrity_error_on_create_is_not_mapped(admin, monkeypatch):
    def boom(name):
        raise sqlite3.IntegrityError("NOT NULL constraint failed: foreign_developments.name")

    monkeypatch.setattr(foreign_offer_routes, "create_foreign_development", boom)
    with pytest.raises(sqlite3.IntegrityError, match="NOT NULL"):
        _create(admin, "Azure Bay")


def test_unexpected_integrity_error_on_assign_is_not_mapped(admin, monkeypatch):
    def boom(offer_id, development_id):
        raise sqlite3.IntegrityError("CHECK constraint failed")

    monkeypatch.setattr(foreign_offer_routes, "set_foreign_offer_development", boom)
    with pytest.raises(sqlite3.IntegrityError, match="CHECK"):
        _assign(admin, 1, None)


def test_operational_error_on_rename_propagates(admin, monkeypatch):
    def boom(development_id, name):
        raise sqlite3.OperationalError("database is locked")

    monkeypatch.setattr(foreign_offer_routes, "rename_foreign_development", boom)
    with pytest.raises(sqlite3.OperationalError):
        admin.post("/crm/foreign-offers/developments/1", json={"name": "X"})


# ---------------------------------------------------------------------------
# AUTHORIZATION
# ---------------------------------------------------------------------------


def _mutations(development_id):
    return [
        ("/crm/foreign-offers/developments", {"name": "Hacked"}),
        (f"/crm/foreign-offers/developments/{development_id}", {"name": "Hacked"}),
        ("/crm/foreign-offers/1/development", {"development_id": development_id}),  # assign
        ("/crm/foreign-offers/5/development", {"development_id": development_id}),  # reassign target below
        ("/crm/foreign-offers/1/development", {"development_id": None}),  # unassign
    ]


@pytest.mark.parametrize("access_level", ["agent", "manager", None])
def test_non_admin_cannot_mutate_developments(client, foreign_db, access_level):
    _login(client)
    azure = _create(client, "Azure Bay").get_json()["item"]
    _assign(client, 5, azure["id"])
    if access_level is None:
        with client.session_transaction() as sess:
            sess.clear()
    else:
        _login(client, access_level)
    before = _db_state(foreign_db)

    for url, payload in _mutations(azure["id"]):
        response = client.post(url, json=payload)
        assert response.status_code in (302, 403), url

    assert _db_state(foreign_db) == before


@pytest.mark.parametrize("access_level", ADMIN_LEVELS)
def test_admin_levels_may_mutate(client, foreign_db, access_level):
    _login(client, access_level)
    assert _create(client, f"Dev {access_level}").status_code == 200


# ---------------------------------------------------------------------------
# DOMIPORTA ISOLATION
# ---------------------------------------------------------------------------


def test_development_routes_keep_publication_state_and_export_timestamps(admin, foreign_db):
    def portal_state():
        conn = _raw_connect(foreign_db)
        try:
            return (
                [tuple(r) for r in conn.execute("SELECT id, last_exported_at FROM foreign_offers ORDER BY id")],
                [tuple(r) for r 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")],
            )
        finally:
            conn.close()

    before = portal_state()
    azure = _create(admin, "Azure Bay").get_json()["item"]
    sol = _create(admin, "Sol Park").get_json()["item"]
    for development_id in (azure["id"], sol["id"], None):
        assert _assign(admin, 1, development_id).status_code == 200
        assert portal_state() == before
    admin.post(f"/crm/foreign-offers/developments/{sol['id']}", json={"name": "Sol Park II"})
    assert portal_state() == before
