"""Fixtures for the CRM security regression tests (session lifecycle, CSRF guard, authorization policy).

Synthetic data only: DATA_DIR and REPO_ROOT point to pytest's tmp_path. Names are prefixed `crm_` so they cannot clash with the
fixtures of the other test modules in this directory.
"""
import sqlite3

import pytest
from werkzeug.security import generate_password_hash

from modules.core import storage_paths

CRM_MASTER, CRM_ANN, CRM_BOB = 101, 102, 103
CRM_LOGINS = {CRM_MASTER: 'mia', CRM_ANN: 'ann', CRM_BOB: 'bob'}
CRM_PASSWORDS = {CRM_MASTER: 'pw-master-101', CRM_ANN: 'pw-ann-102', CRM_BOB: 'pw-bob-103'}
CRM_ANN_OFFER, CRM_BOB_OFFER = 501, 601


@pytest.fixture()
def crm_env(tmp_path, monkeypatch):
    monkeypatch.setenv(storage_paths.DATA_DIR_ENV_VAR, str(tmp_path))
    monkeypatch.setattr(storage_paths, 'REPO_ROOT', tmp_path)
    agents = storage_paths.agents_db_path()
    agents.parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(agents)
    conn.executescript(
        """
        CREATE TABLE agents_v2 (id INTEGER PRIMARY KEY, login TEXT, password_hash TEXT, first_name TEXT, last_name TEXT,
            email TEXT, phone TEXT, license TEXT, access_level TEXT, is_active INTEGER, created_at TEXT, updated_at TEXT);
        CREATE TABLE branches_v2 (id INTEGER PRIMARY KEY, code TEXT, name TEXT, title TEXT, image_url TEXT, info1 TEXT, info2 TEXT, is_active INTEGER, created_at TEXT, updated_at TEXT);
        CREATE TABLE roles_v2 (id INTEGER PRIMARY KEY, code TEXT, name TEXT, description TEXT, is_active INTEGER);
        CREATE TABLE agent_branches_v2 (agent_id INTEGER, branch_id INTEGER, is_primary INTEGER, created_at TEXT);
        CREATE TABLE agent_roles_v2 (agent_id INTEGER, role_id INTEGER, created_at TEXT);
        """
    )
    for uid, level in ((CRM_MASTER, 'master'), (CRM_ANN, 'agent'), (CRM_BOB, 'agent')):
        login = CRM_LOGINS[uid]
        conn.execute('INSERT INTO agents_v2 VALUES (?,?,?,?,?,?,?,?,?,1,?,?)',
                     (uid, login, generate_password_hash(CRM_PASSWORDS[uid]), login.title(), 'Test', f'{login}@example.invalid',
                      f'600{uid}', f'LIC-{uid}', level, 't', 't'))
    conn.commit()
    conn.close()
    conn = sqlite3.connect(storage_paths.idb_db_path())
    conn.executescript("CREATE TABLE estatedata (ID INTEGER PRIMARY KEY, ID_agenta INTEGER, Status_oferty TEXT, Cena TEXT, Typ_nieruchomosci TEXT, Miejscowosc TEXT, Tytul TEXT);")
    for offer, owner in ((CRM_ANN_OFFER, CRM_ANN), (CRM_BOB_OFFER, CRM_BOB)):
        conn.execute("INSERT INTO estatedata VALUES (?,?,'aktywna','100','mieszkanie','Gdansk','T')", (offer, owner))
    conn.commit()
    conn.close()
    return tmp_path


@pytest.fixture()
def crm_login():
    """crm_login(app, user_id) -> a NEW test client logged in through the real login form."""
    def login(app, who):
        client = app.test_client()
        response = client.post('/crm/', data={'username': CRM_LOGINS[who], 'password': CRM_PASSWORDS[who]})
        assert response.status_code == 302, 'login failed'
        return client
    return login


@pytest.fixture()
def crm_set_agent(crm_env):
    """crm_set_agent(user_id, **columns): change an agents_v2 row directly (what an administrator / dbshell would do)."""
    def update(uid, **columns):
        conn = sqlite3.connect(storage_paths.agents_db_path())
        conn.execute('UPDATE agents_v2 SET ' + ', '.join(f'{k} = ?' for k in columns) + ' WHERE id = ?', (*columns.values(), uid))
        conn.commit()
        conn.close()
    return update
