-- V75: 회계 결산 (Accounting Close)
-- period_close(V29 운영 마감)와 별도로 월/분기/연 단위 회계 마감을 관리한다.
-- 결산 시 contract_accounting_entry.journal_no 를 채번해 미전기→전기 처리하고,
-- 결산 시점의 계정과목별 잔액을 account_balance_snapshot 으로 보존한다.

-- ============================================================
-- 1. accounting_close: 결산 헤더
-- ============================================================
CREATE TABLE accounting_close (
    close_id         BIGSERIAL      PRIMARY KEY,
    close_period     VARCHAR(10)    NOT NULL,                    -- YYYY-MM / YYYY-Qn / YYYY
    close_type       VARCHAR(10)    NOT NULL,                    -- MONTHLY / QUARTERLY / YEARLY
    close_status     VARCHAR(10)    NOT NULL DEFAULT 'DRAFT',    -- DRAFT / CLOSED / REOPENED
    journal_prefix   VARCHAR(20)    NOT NULL,                    -- 분개번호 채번 prefix (예: 2025-03)
    journal_count    INTEGER        NOT NULL DEFAULT 0,          -- 채번된 분개 수
    total_debit      NUMERIC(18,2)  NOT NULL DEFAULT 0,
    total_credit     NUMERIC(18,2)  NOT NULL DEFAULT 0,
    closed_at        TIMESTAMP,
    closed_by        BIGINT,
    reopened_at      TIMESTAMP,
    reopened_by      BIGINT,
    reopen_reason    VARCHAR(200),
    created_at       TIMESTAMP      NOT NULL DEFAULT now(),
    created_by       BIGINT,
    updated_at       TIMESTAMP      NOT NULL DEFAULT now(),
    updated_by       BIGINT,
    UNIQUE (close_period, close_type),
    CONSTRAINT chk_acc_type   CHECK (close_type   IN ('MONTHLY','QUARTERLY','YEARLY')),
    CONSTRAINT chk_acc_status CHECK (close_status IN ('DRAFT','CLOSED','REOPENED'))
);
COMMENT ON TABLE  accounting_close                IS '회계 결산 헤더';
COMMENT ON COLUMN accounting_close.close_period   IS '결산 기간 키 (월: YYYY-MM, 분기: YYYY-Q1, 연: YYYY)';
COMMENT ON COLUMN accounting_close.close_status   IS 'DRAFT=초안, CLOSED=마감완료, REOPENED=재오픈';
COMMENT ON COLUMN accounting_close.journal_prefix IS '분개 채번 prefix (월결산 시 YYYY-MM)';

CREATE INDEX idx_ac_period ON accounting_close(close_period);
CREATE INDEX idx_ac_status ON accounting_close(close_status);

-- ============================================================
-- 2. account_balance_snapshot: 결산 시점 잔액 스냅샷
-- ============================================================
CREATE TABLE account_balance_snapshot (
    snapshot_id    BIGSERIAL      PRIMARY KEY,
    close_id       BIGINT         NOT NULL REFERENCES accounting_close(close_id) ON DELETE CASCADE,
    account_code   VARCHAR(20)    NOT NULL,                  -- account_code FK 미강제(미시드 코드도 허용)
    account_name   VARCHAR(100),
    account_type   VARCHAR(10),                              -- DEBIT/CREDIT/BOTH 캐시
    debit_total    NUMERIC(18,2)  NOT NULL DEFAULT 0,
    credit_total   NUMERIC(18,2)  NOT NULL DEFAULT 0,
    balance        NUMERIC(18,2)  NOT NULL DEFAULT 0,        -- debit_total - credit_total
    created_at     TIMESTAMP      NOT NULL DEFAULT now(),
    UNIQUE (close_id, account_code)
);
COMMENT ON TABLE  account_balance_snapshot         IS '결산 시점 계정과목별 잔액 스냅샷';
COMMENT ON COLUMN account_balance_snapshot.balance IS '차변합 - 대변합';

CREATE INDEX idx_abs_close   ON account_balance_snapshot(close_id);
CREATE INDEX idx_abs_account ON account_balance_snapshot(account_code);
