"""
Integration test for services/usage_log.py against a real (temporary)
SQLite file — verifies the table is created and rows are queryable exactly
the way the operator would query them from a terminal.
"""

import os
import sqlite3
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from financegpt_bot import config          # noqa: E402
from financegpt_bot.services import usage_log  # noqa: E402


def test_log_action_creates_table_and_row(tmp_path, monkeypatch):
    monkeypatch.setattr(config, "DATA_DIR", str(tmp_path))

    usage_log.log_action(123, "Ali", "Rezaei", "start")
    usage_log.log_action(456, "Sara", None, "price_lookup", "USDT")

    db_path = os.path.join(str(tmp_path), "usage_log.db")
    assert os.path.exists(db_path)

    conn = sqlite3.connect(db_path)
    rows = conn.execute(
        "SELECT chat_id, first_name, last_name, action, detail FROM usage_log ORDER BY id"
    ).fetchall()
    conn.close()

    assert rows == [
        ("123", "Ali", "Rezaei", "start", None),
        ("456", "Sara", None, "price_lookup", "USDT"),
    ]


def test_log_action_never_raises_on_bad_data_dir(monkeypatch):
    # DATA_DIR pointing at something that can't hold files (e.g. a file, not
    # a directory) must not crash the bot — logging failures are swallowed.
    monkeypatch.setattr(config, "DATA_DIR", "/definitely/not/a/real/path/???")
    usage_log.log_action(1, "X", "Y", "start")  # should not raise
