from fastapi import APIRouter, HTTPException

from backend.db.database import get_connection
from pydantic import BaseModel

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


class OpeningBalanceBody(BaseModel):
    period_start: str  # YYYY-MM-DD
    amount: float


@router.get("")
def list_accounts():
    conn = get_connection()
    try:
        rows = conn.execute(
            """SELECT a.id, a.bank_id, a.external_id, a.name, b.code as bank_code, b.name as bank_name, b.is_salary
               FROM accounts a JOIN banks b ON a.bank_id = b.id ORDER BY b.code, a.external_id"""
        ).fetchall()
        return [dict(r) for r in rows]
    finally:
        conn.close()


@router.post("/{account_id}/opening-balance")
def set_opening_balance(account_id: int, body: OpeningBalanceBody):
    conn = get_connection()
    try:
        conn.execute(
            """INSERT INTO opening_balances (account_id, period_start, amount) VALUES (?, ?, ?)
               ON CONFLICT(account_id, period_start) DO UPDATE SET amount = excluded.amount""",
            (account_id, body.period_start, body.amount),
        )
        conn.commit()
        return {"account_id": account_id, "period_start": body.period_start, "amount": body.amount}
    finally:
        conn.close()
