from fastapi import APIRouter

from backend.db.database import get_connection
from backend.services.settings_service import get_income_settings, set_income_settings
from pydantic import BaseModel

router = APIRouter(prefix="/api/settings", tags=["settings"])


class IncomeSettingsBody(BaseModel):
    count_income_only_salary_card: bool
    salary_account_id: int | None = None


@router.get("/income")
def get_income_settings_api():
    """Настройки учёта доходов + список счетов зарплатного банка для выбора карты."""
    only_card, account_id = get_income_settings()
    conn = get_connection()
    try:
        rows = conn.execute("""
            SELECT a.id, a.external_id, a.name, b.name as bank_name
            FROM accounts a
            JOIN banks b ON a.bank_id = b.id
            WHERE b.is_salary = 1
            ORDER BY a.external_id
        """).fetchall()
        salary_accounts = [dict(r) for r in rows]
    finally:
        conn.close()
    return {
        "count_income_only_salary_card": only_card,
        "salary_account_id": account_id,
        "salary_accounts": salary_accounts,
    }


@router.put("/income")
def put_income_settings(body: IncomeSettingsBody):
    set_income_settings(body.count_income_only_salary_card, body.salary_account_id)
    return {"count_income_only_salary_card": body.count_income_only_salary_card, "salary_account_id": body.salary_account_id}


@router.get("/exclude-transfers")
def get_exclude_transfers_api():
    from backend.services.settings_service import get_exclude_transfers
    return {"exclude_transfers": get_exclude_transfers()}


class ExcludeTransfersBody(BaseModel):
    exclude_transfers: bool


@router.put("/exclude-transfers")
def put_exclude_transfers_api(body: ExcludeTransfersBody):
    from backend.services.settings_service import set_exclude_transfers
    set_exclude_transfers(body.exclude_transfers)
    return {"exclude_transfers": body.exclude_transfers}
