from decimal import Decimal
from app.core.database import get_connection
from app.modules.general_ledger.sql import GENERAL_LEDGER_SQL

def D(x) -> Decimal:
    return Decimal(str(x or 0))

def fetch_general_ledger(account_id: int, date_from: str, date_to: str):

    with get_connection() as conn, conn.cursor() as cur:

        # ① 科目确认
        cur.execute("""
            SELECT account_code, account_name
              FROM accounts
             WHERE account_id = %s
               AND is_active = true
        """, (account_id,))
        acc = cur.fetchone()
        if not acc:
            return None

        # ② 元帳明细
        cur.execute(
            GENERAL_LEDGER_SQL,
            {
                "account_id": account_id,
                "date_from": date_from,
                "date_to": date_to
            }
        )
        rows = cur.fetchall()

        balance = Decimal("0")
        lines = []

        for r in rows:
            balance += D(r["debit"]) - D(r["credit"])
            lines.append({
                "journal_date": r["journal_date"],
                "description": r["description"],
                "debit": str(D(r["debit"])),
                "credit": str(D(r["credit"])),
                "balance": str(balance)
            })

    return {
        "account": {
            "account_code": acc["account_code"],
            "account_name": acc["account_name"]
        },
        "lines": lines
    }
