-- V64: 계약 회계분개 엔트리 테이블

CREATE TABLE contract_accounting_entry (
    entry_id       BIGSERIAL      PRIMARY KEY,
    contract_id    BIGINT         NOT NULL REFERENCES contract(contract_id),
    payment_id     BIGINT         REFERENCES payment(payment_id),
    entry_date     DATE           NOT NULL,
    debit_account  VARCHAR(20)    NOT NULL,
    credit_account VARCHAR(20)    NOT NULL,
    amount         NUMERIC(18,2)  NOT NULL,
    description    VARCHAR(200),
    journal_no     VARCHAR(30),
    created_at     TIMESTAMP      NOT NULL DEFAULT now()
);

COMMENT ON TABLE contract_accounting_entry IS '계약 회계 분개 엔트리';
COMMENT ON COLUMN contract_accounting_entry.debit_account  IS '차변 계정코드 (예: 8350 지급수수료)';
COMMENT ON COLUMN contract_accounting_entry.credit_account IS '대변 계정코드 (예: 2530 미지급금)';
COMMENT ON COLUMN contract_accounting_entry.journal_no     IS '마감 시 채번. NULL=미전기';

CREATE INDEX idx_cae_journal  ON contract_accounting_entry(journal_no);
CREATE INDEX idx_cae_date     ON contract_accounting_entry(entry_date);
CREATE INDEX idx_cae_contract ON contract_accounting_entry(contract_id, entry_date);
CREATE INDEX idx_cae_unposted ON contract_accounting_entry(entry_date) WHERE journal_no IS NULL;
