-- ---------------------------------------------------------------------------
-- lg 모듈 (원장/ledger) - 복식부기 전표/원장/계정잔액 스키마 (prefix 40)
-- Loaded after 00-base.sql by docker-entrypoint-initdb.d.
-- lg 서비스/배치가 채우는 전표(voucher) + 원장 라인(ledger_line) + 계정잔액 테이블.
-- ---------------------------------------------------------------------------

-- 전표 (voucher) - 하나의 회계 이벤트(매입전기/정산전기/조정/대체 등)의 헤더
CREATE SEQUENCE IF NOT EXISTS lg_voucher_seq;
CREATE TABLE IF NOT EXISTS lg_voucher (
    voucher_id   BIGINT PRIMARY KEY,
    voucher_type TEXT NOT NULL,               -- POST/DOUBLE/ADJ/REVERSE/TRANSFER/SETTLE/ACQ/FEE
    ref_id       BIGINT NOT NULL DEFAULT 0,   -- 연계 매입/정산 ID
    biz_date     DATE NOT NULL,
    status       TEXT NOT NULL DEFAULT 'D',   -- D=작성, P=전기, M=대사, S=마감연계, X=취소
    memo         TEXT NOT NULL DEFAULT '',
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- 원장 라인 (ledger_line) - 복식부기 차변(D)/대변(C) 개별 분개
CREATE SEQUENCE IF NOT EXISTS lg_line_seq;
CREATE TABLE IF NOT EXISTS lg_ledger_line (
    line_id      BIGINT PRIMARY KEY,
    voucher_id   BIGINT NOT NULL,
    acct         TEXT NOT NULL,               -- 계정과목: RECV/MERCH_PAY/FEE_INC/CASH/ADJ ...
    dc           TEXT NOT NULL,               -- D=차변(debit), C=대변(credit)
    amount       BIGINT NOT NULL,
    merchant_id  TEXT NOT NULL DEFAULT '',
    biz_date     DATE NOT NULL,
    status       TEXT NOT NULL DEFAULT 'posted', -- posted / closed
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_lg_line_voucher ON lg_ledger_line(voucher_id);
CREATE INDEX IF NOT EXISTS ix_lg_line_acct    ON lg_ledger_line(acct, biz_date);

-- 계정잔액 (account balance) - 계정과목 x 영업일 누계
CREATE TABLE IF NOT EXISTS lg_account_bal (
    acct          TEXT NOT NULL,
    biz_date      DATE NOT NULL,
    debit_total   BIGINT NOT NULL DEFAULT 0,
    credit_total  BIGINT NOT NULL DEFAULT 0,
    balance       BIGINT NOT NULL DEFAULT 0,  -- 차변 - 대변
    updated_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (acct, biz_date)
);

-- 가맹점 잔액 (merchant balance) - 가맹점 x 영업일 미지급/미수 누계
CREATE TABLE IF NOT EXISTS lg_merch_bal (
    merchant_id   TEXT NOT NULL,
    biz_date      DATE NOT NULL,
    debit_total   BIGINT NOT NULL DEFAULT 0,
    credit_total  BIGINT NOT NULL DEFAULT 0,
    balance       BIGINT NOT NULL DEFAULT 0,
    updated_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (merchant_id, biz_date)
);

-- 시산표 (trial balance) - 배치가 계정별로 채움
CREATE TABLE IF NOT EXISTS lg_trial_bal (
    acct          TEXT NOT NULL,
    biz_date      DATE NOT NULL,
    debit_total   BIGINT NOT NULL DEFAULT 0,
    credit_total  BIGINT NOT NULL DEFAULT 0,
    diff          BIGINT NOT NULL DEFAULT 0,  -- 차변 - 대변 (0 이어야 정상)
    updated_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (acct, biz_date)
);
