from backend.db.database import get_connection


def get_income_settings() -> tuple[bool, int | None]:
    """Возвращает (count_income_only_salary_card, salary_account_id)."""
    conn = get_connection()
    try:
        row = conn.execute(
            "SELECT value FROM app_settings WHERE key = ?",
            ("count_income_only_salary_card",),
        ).fetchone()
        only_salary_card = row and row["value"] == "1"
        row2 = conn.execute(
            "SELECT value FROM app_settings WHERE key = ?",
            ("salary_account_id",),
        ).fetchone()
        account_id = int(row2["value"]) if row2 and row2["value"] else None
        return (only_salary_card, account_id)
    finally:
        conn.close()


def set_income_settings(count_income_only_salary_card: bool, salary_account_id: int | None) -> None:
    conn = get_connection()
    try:
        conn.execute(
            "INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)",
            ("count_income_only_salary_card", "1" if count_income_only_salary_card else "0"),
        )
        conn.execute(
            "INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)",
            ("salary_account_id", str(salary_account_id) if salary_account_id else ""),
        )
        conn.commit()
    finally:
        conn.close()


def get_exclude_transfers() -> bool:
    """Игнорировать операции с «Перевод» в расчётах."""
    conn = get_connection()
    try:
        row = conn.execute(
            "SELECT value FROM app_settings WHERE key = ?",
            ("exclude_transfers",),
        ).fetchone()
        return row and row["value"] == "1"
    finally:
        conn.close()


def set_exclude_transfers(value: bool) -> None:
    conn = get_connection()
    try:
        conn.execute(
            "INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)",
            ("exclude_transfers", "1" if value else "0"),
        )
        conn.commit()
    finally:
        conn.close()
