"""SnelStart bank transaction import boundary."""

from __future__ import annotations

from app.services.snelstart.connection import get_connection, integration_enabled, is_client_connected
from app.services.snelstart.models import BankImportResult, BankImportRow
from app.store import store


def import_bank_transactions_for_client(client_id: str) -> list[BankImportRow]:
    """
    Import bank transactions from SnelStart for one client.

    Returns an empty list until a real SnelStart API is connected.
    """
    client = store.get_client(client_id)
    legacy_flag = bool(client and client.snelstart)
    if not integration_enabled() or not is_client_connected(client_id, legacy_snelstart=legacy_flag):
        return []

    # Future: call SnelStart bank API and map rows → BankImportRow
    return []


def import_bank_transactions_all() -> BankImportResult:
    """Attempt import for every client. Never fabricates transactions."""
    if not integration_enabled():
        return BankImportResult(
            imported=0,
            clientsChecked=0,
            connectedClients=0,
            integrationEnabled=False,
            message="SnelStart integration is not enabled. Connect the integration to import bank transactions.",
        )

    imported = 0
    clients_checked = 0
    connected_clients = 0

    for client in store.snapshot().clients:
        info = get_connection(client.id, legacy_snelstart=client.snelstart)
        if not info.isConnected:
            continue
        connected_clients += 1
        clients_checked += 1
        rows = import_bank_transactions_for_client(client.id)
        for row in rows:
            store.import_bank_transaction(client.id, row)
            imported += 1

    if connected_clients == 0:
        message = "SnelStart is not connected for any client. No transactions were imported."
    elif imported == 0:
        message = "SnelStart is connected but returned no new bank transactions."
    else:
        message = f"Imported {imported} bank transaction(s) from SnelStart."

    return BankImportResult(
        imported=imported,
        clientsChecked=clients_checked,
        connectedClients=connected_clients,
        integrationEnabled=True,
        message=message,
    )
