-- V29 §5B 공통 전자결재(F028) — 결재 문서 + 다단계 결재선 + 처리 이력 (멱등·tenant_id)
-- 규칙(불변): V1~V28 불변. 전부 CREATE ... IF NOT EXISTS 로 재실행 안전.
--             WISE/UIWS TB_APPROVAL/LINE/HISTORY 패턴 이식(kintex work 모듈 컨벤션: varchar id·tenant_id·소문자 테이블).
-- 상태(문서): DRAFT → SUBMITTED → IN_PROGRESS → APPROVED | REJECTED  (+ CANCELED 회수)
-- 결재선(단계): WAIT / CURRENT / APPROVED / REJECTED / SKIPPED
-- 이력(액션): SUBMIT / APPROVE / REJECT / RESUBMIT / CANCEL
-- M6 서류 연계: ref_type='DOCUMENT' + ref_id(docType/booth 등)로 서류 검수 흐름과 느슨 결합.

-- 1) 결재 문서 -----------------------------------------------------------------
CREATE TABLE IF NOT EXISTS approval (
    tenant_id    varchar(40)  NOT NULL DEFAULT 'KINTEX',
    id           varchar(40)  NOT NULL,
    event_id     varchar(40),
    doc_type     varchar(30)  NOT NULL DEFAULT 'GENERAL',
    title        varchar(300) NOT NULL,
    content      text,
    ref_type     varchar(30),                       -- M6 연계 대상 유형(예: DOCUMENT)
    ref_id       varchar(120),                       -- M6 연계 대상 식별(예: 부스/docType)
    drafter_id   varchar(40)  NOT NULL,
    drafter_name varchar(120),
    status       varchar(20)  NOT NULL DEFAULT 'DRAFT',
    cur_step     integer      NOT NULL DEFAULT 0,     -- 현재 진행 단계(1부터, DRAFT=0)
    version      integer      NOT NULL DEFAULT 1,     -- 재상신 시 증가
    submitted_at timestamptz,
    completed_at timestamptz,
    created_at   timestamptz  NOT NULL DEFAULT now(),
    updated_at   timestamptz  NOT NULL DEFAULT now(),
    UNIQUE (id),                                        -- 자식 FK(approval_id→approval.id) 대상 보존
    PRIMARY KEY (tenant_id, id)                          -- ★표준: tenant_id 선두 복합 PK
);
CREATE INDEX IF NOT EXISTS idx_approval_drafter ON approval (drafter_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_approval_event   ON approval (event_id, status);
CREATE INDEX IF NOT EXISTS idx_approval_ref     ON approval (ref_type, ref_id);
CREATE INDEX IF NOT EXISTS idx_approval_tenant  ON approval (tenant_id, status, created_at DESC);

-- 2) 결재선 단계 ---------------------------------------------------------------
CREATE TABLE IF NOT EXISTS approval_line (
    tenant_id     varchar(40) NOT NULL DEFAULT 'KINTEX',
    id            varchar(40) NOT NULL,
    approval_id   varchar(40) NOT NULL REFERENCES approval(id) ON DELETE CASCADE,
    step_no       integer     NOT NULL,              -- 1부터 연속
    approver_id   varchar(40) NOT NULL,
    approver_name varchar(120),
    line_status   varchar(20) NOT NULL DEFAULT 'WAIT',
    acted_at      timestamptz,
    comment       varchar(500),
    PRIMARY KEY (tenant_id, id)                          -- ★표준
);
CREATE INDEX IF NOT EXISTS idx_approval_line          ON approval_line (approval_id, step_no);
CREATE INDEX IF NOT EXISTS idx_approval_line_approver ON approval_line (approver_id, line_status);

-- 3) 처리 이력(감사·타임라인, 불변) --------------------------------------------
CREATE TABLE IF NOT EXISTS approval_history (
    tenant_id   varchar(40) NOT NULL DEFAULT 'KINTEX',
    id          varchar(40) NOT NULL,
    approval_id varchar(40) NOT NULL REFERENCES approval(id) ON DELETE CASCADE,
    step_no     integer,
    actor_id    varchar(40) NOT NULL,
    actor_name  varchar(120),
    action      varchar(20) NOT NULL,
    comment     varchar(500),
    acted_at    timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (tenant_id, id)                          -- ★표준
);
CREATE INDEX IF NOT EXISTS idx_approval_history ON approval_history (approval_id, acted_at);
