"""INV-FIX-002 / INV-AUD-006: /crm/update_profile persists contact data without a password change.

Throwaway agents.db (storage_paths.agents_db_path patched to tmp_path).
"""
import sqlite3

import pytest
from werkzeug.security import check_password_hash, generate_password_hash

import InvestmentManager.routes.dashboard as dashboard
from modules.core import storage_paths

OLD = ("old@example.com", "111", "L1")
# S3.8: new passwords must satisfy the policy (>= 12 characters, not the login / identity data)
NEW_PASSWORD = "nowe-haslo-2026"


@pytest.fixture()
def agents_db(tmp_path, monkeypatch):
    # Profile writes now also coordinate against the domestic state/history.
    monkeypatch.setenv('DATA_DIR',str(tmp_path))
    path = tmp_path / "agents.db"
    conn = sqlite3.connect(path)
    conn.execute("CREATE TABLE agents_v2 (id INTEGER PRIMARY KEY, login TEXT, first_name TEXT, last_name TEXT, email TEXT, phone TEXT, license TEXT,"
                 " password_hash TEXT, updated_at TEXT)")
    conn.execute("INSERT INTO agents_v2 VALUES (1, 'stary.agent', 'Stary', 'Agent', ?, ?, ?, ?, NULL)", (*OLD, generate_password_hash("stare-haslo")))
    conn.execute("INSERT INTO agents_v2 VALUES (2, 'inny.agent', 'Inny', 'Agent', 'other@example.com', '999', 'L9', NULL, NULL)")
    conn.commit()
    conn.close()
    monkeypatch.setattr(storage_paths, "agents_db_path", lambda: path)
    return path


@pytest.fixture()
def agent(client):
    with client.session_transaction() as sess:
        sess["user_id"] = 1
        sess["access_level"] = "agent"
        sess["email"], sess["phone"], sess["licence"] = OLD
    return client


def _row(path, agent_id=1):
    conn = sqlite3.connect(path)
    try:
        return conn.execute("SELECT email, phone, license, password_hash, updated_at FROM agents_v2 WHERE id = ?",
                            (agent_id,)).fetchone()
    finally:
        conn.close()


def _session(client):
    with client.session_transaction() as sess:
        return (sess.get("email"), sess.get("phone"), sess.get("licence")), sess.get("_flashes", [])


CONTACT = {"email": "nowy@example.com", "telefon": "222 333 444", "licencja": "L2"}


def test_contact_change_is_saved_without_password_change(agent, agents_db):
    response = agent.post("/crm/update_profile", data=CONTACT)

    assert response.status_code == 302
    email, phone, license_, password_hash, updated_at = _row(agents_db)
    assert (email, phone, license_) == ("nowy@example.com", "222 333 444", "L2")
    assert updated_at is not None
    assert check_password_hash(password_hash, "stare-haslo")  # password untouched
    session_contact, flashes = _session(agent)
    assert session_contact == ("nowy@example.com", "222 333 444", "L2")
    assert flashes == [("success", "✅ Dane zostały zaktualizowane.")]
    assert _row(agents_db, 2)[:3] == ("other@example.com", "999", "L9")  # only the logged-in agent


def test_saved_contact_survives_a_fresh_connection_and_a_second_update(agent, agents_db):
    agent.post("/crm/update_profile", data=CONTACT)
    agent.post("/crm/update_profile", data=dict(CONTACT, telefon="555"))

    assert _row(agents_db)[:3] == ("nowy@example.com", "555", "L2")


def test_password_change_still_works_and_saves_contact_too(agent, agents_db):
    agent.post("/crm/update_profile", data=dict(CONTACT, current_password="stare-haslo",
                                                 new_password=NEW_PASSWORD, confirm_password=NEW_PASSWORD))

    email, _, _, password_hash, _ = _row(agents_db)
    assert email == "nowy@example.com"
    assert check_password_hash(password_hash, NEW_PASSWORD)
    assert _session(agent)[1] == [("info", "✅ Hasło zostało zmienione.")]


@pytest.mark.parametrize("current, new, confirm, message", [
    ("zle-haslo", NEW_PASSWORD, NEW_PASSWORD, "❌ Błędne aktualne hasło."),
    ("stare-haslo", NEW_PASSWORD, "inne-haslo-2026", "❌ Nowe hasła się nie zgadzają."),
])
def test_rejected_password_change_keeps_the_old_password(agent, agents_db, current, new, confirm, message):
    agent.post("/crm/update_profile", data=dict(CONTACT, current_password=current,
                                                 new_password=new, confirm_password=confirm))

    assert check_password_hash(_row(agents_db)[3], "stare-haslo")
    assert _session(agent)[1] == [("info", message)]
    # Contact data is changed independently of the password (existing behaviour).
    assert _row(agents_db)[0] == "nowy@example.com"


class _FailingCommit:
    """Proxy for the real sqlite3 connection whose commit fails like a locked/read-only DB."""

    def __init__(self, conn):
        self._conn = conn

    def __getattr__(self, name):
        return getattr(self._conn, name)

    def commit(self):
        raise sqlite3.OperationalError("database is locked")


def test_write_error_shows_error_and_changes_nothing(agent, agents_db, monkeypatch):
    real_manager = dashboard.DatabaseConnectionManager

    class FailingManager(real_manager):
        def __enter__(self):
            return _FailingCommit(super().__enter__())

    monkeypatch.setattr(dashboard, "DatabaseConnectionManager", FailingManager)

    agent.post("/crm/update_profile", data=dict(CONTACT, current_password="stare-haslo",
                                                 new_password=NEW_PASSWORD, confirm_password=NEW_PASSWORD))

    email, phone, license_, password_hash, _ = _row(agents_db)
    assert (email, phone, license_) == OLD
    assert check_password_hash(password_hash, "stare-haslo")
    session_contact, flashes = _session(agent)
    assert session_contact == OLD  # the session does not claim a change that was not saved
    assert flashes == [("error", "Błąd przy aktualizacji danych.")]


def test_missing_table_is_reported_as_error(agent, tmp_path, monkeypatch):
    monkeypatch.setenv('DATA_DIR',str(tmp_path))
    empty = tmp_path / "empty_agents.db"
    sqlite3.connect(empty).close()
    monkeypatch.setattr(storage_paths, "agents_db_path", lambda: empty)

    agent.post("/crm/update_profile", data=CONTACT)

    session_contact, flashes = _session(agent)
    assert session_contact == OLD
    assert flashes == [("error", "Błąd przy aktualizacji danych.")]
