-- 017: ASC 606 accounting journal entries (clearing-service)
CREATE TABLE IF NOT EXISTS journal_entries (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    entry_date DATE NOT NULL,
    debit_account VARCHAR(50) NOT NULL,
    debit_amount NUMERIC(15,2) NOT NULL,
    credit_account VARCHAR(50) NOT NULL,
    credit_amount NUMERIC(15,2) NOT NULL,
    memo VARCHAR(500),
    reference_type VARCHAR(30),
    reference_id UUID,
    tx_hash VARCHAR(66),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_journal_entry_date ON journal_entries(entry_date);
CREATE INDEX idx_journal_reference ON journal_entries(reference_type, reference_id);
CREATE INDEX idx_journal_debit_account ON journal_entries(debit_account);
CREATE INDEX idx_journal_credit_account ON journal_entries(credit_account);

-- Chart of Accounts reference (comment only, not enforced)
-- 1001 cash                          现金及等价物
-- 1002 cash_stablecoin               稳定币资产
-- 1101 accounts_receivable_issuer    应收账款-发行方
-- 1102 accounts_receivable_breakage  应收账款-Breakage分润
-- 2001 deferred_revenue              递延收入(券未兑付负债)
-- 2002 user_deposits                 用户托管资金
-- 2003 guarantee_funds_held          发行方保障资金
-- 4001 revenue_trading_fee           交易手续费收入
-- 4002 revenue_issuance_fee          发行服务费收入
-- 4003 revenue_breakage_share        Breakage分润收入
-- 4004 revenue_vas                   增值服务收入
-- 4005 revenue_earned                已确认收入(发行方侧)
-- 4006 revenue_breakage              Breakage收入(发行方侧)
