# backend/app/modules/trial_balance/sql.py

TRIAL_BALANCE_SQL = """
WITH accounts_base AS (
    SELECT
        a.account_id,
        a.account_code,
        a.account_name,
        a.account_type
    FROM accounts a
    WHERE a.is_active = true
),

opening AS (
    SELECT
        jl.account_id,
        SUM(jl.debit)  AS opening_debit,
        SUM(jl.credit) AS opening_credit
    FROM journal_entries je
    JOIN journal_lines jl ON jl.journal_entry_id = je.journal_entry_id
    WHERE je.description = '前期残高'
      AND je.entry_date = %(start_date)s
      AND je.is_deleted = false
    GROUP BY jl.account_id
),

period AS (
    SELECT
        jl.account_id,
        SUM(jl.debit)  AS period_debit,
        SUM(jl.credit) AS period_credit
    FROM journal_entries je
    JOIN journal_lines jl ON jl.journal_entry_id = je.journal_entry_id
    LEFT JOIN journal_entries child ON child.parent_entry_id = je.journal_entry_id
    WHERE je.entry_date BETWEEN %(start_date)s AND %(end_date)s
      AND je.description <> '前期残高'
      AND je.is_deleted = false
      -- 逆仕訳を除外（[逆仕訳]プレフィックスを持つ仕訳）
      AND je.description NOT LIKE '[逆仕訳]%'
      -- 子仕訳（修正後仕訳）を持つ修正前の仕訳を除外
      AND child.journal_entry_id IS NULL
    GROUP BY jl.account_id
)

SELECT
    a.account_code,
    a.account_name,
    a.account_type,

    COALESCE(o.opening_debit, 0)  AS opening_debit,
    COALESCE(o.opening_credit, 0) AS opening_credit,
    COALESCE(p.period_debit, 0)   AS period_debit,
    COALESCE(p.period_credit, 0)  AS period_credit,

    CASE
        WHEN (
            COALESCE(o.opening_debit, 0)
          - COALESCE(o.opening_credit, 0)
          + COALESCE(p.period_debit, 0)
          - COALESCE(p.period_credit, 0)
        ) > 0
        THEN (
            COALESCE(o.opening_debit, 0)
          - COALESCE(o.opening_credit, 0)
          + COALESCE(p.period_debit, 0)
          - COALESCE(p.period_credit, 0)
        )
        ELSE 0
    END AS closing_debit,

    CASE
        WHEN (
            COALESCE(o.opening_debit, 0)
          - COALESCE(o.opening_credit, 0)
          + COALESCE(p.period_debit, 0)
          - COALESCE(p.period_credit, 0)
        ) < 0
        THEN ABS(
            COALESCE(o.opening_debit, 0)
          - COALESCE(o.opening_credit, 0)
          + COALESCE(p.period_debit, 0)
          - COALESCE(p.period_credit, 0)
        )
        ELSE 0
    END AS closing_credit

FROM accounts_base a
LEFT JOIN opening o ON o.account_id = a.account_id
LEFT JOIN period  p ON p.account_id = a.account_id
ORDER BY a.account_code;
"""
