from fastapi import APIRouter, HTTPException

from backend.db.database import get_connection

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


@router.get("")
def list_banks():
    conn = get_connection()
    try:
        rows = conn.execute(
            "SELECT id, code, name, is_salary FROM banks ORDER BY code"
        ).fetchall()
        return [dict(r) for r in rows]
    finally:
        conn.close()


@router.put("/salary/{bank_id}")
def set_salary_bank(bank_id: int):
    conn = get_connection()
    try:
        conn.execute("UPDATE banks SET is_salary = 0")
        cur = conn.execute("UPDATE banks SET is_salary = 1 WHERE id = ?", (bank_id,))
        conn.commit()
        if cur.rowcount == 0:
            raise HTTPException(status_code=404, detail="Bank not found")
        return {"salary_bank_id": bank_id}
    finally:
        conn.close()
