/**
 * 결재(APPROVAL) 시스템 테이블 idempotent 마이그레이션
 *  - wace_plm 의 APPROVAL / ROUTE / APPROVAL_TARGET / INBOXTASK / APPROVAL_KIND / AMARANTH_APPROVAL 1:1 포팅
 *  - 부팅 시 1회 실행
 */
import { getPool } from "../database/db";
import { logger } from "../utils/logger";

const STATEMENTS: string[] = [
  // ── APPROVAL : 결재 마스터 (한 결재 건 = 1 row) ────────────────
  `CREATE TABLE IF NOT EXISTS approval (
     objid          BIGINT PRIMARY KEY,
     target_objid   BIGINT,
     target_type    VARCHAR(50),       -- ECR_MNG, CUSTOMER_MNG, EO_MNG, ASMNG, CSM, ...
     approval_seq   BIGINT,
     system_type    VARCHAR(50),
     status         VARCHAR(20)  DEFAULT 'inProcess',  -- inProcess / complete / reject / cancel
     regdate        TIMESTAMP    DEFAULT NOW()
   )`,
  `CREATE INDEX IF NOT EXISTS idx_approval_target  ON approval (target_objid)`,
  `CREATE INDEX IF NOT EXISTS idx_approval_type    ON approval (target_type)`,
  `CREATE INDEX IF NOT EXISTS idx_approval_status  ON approval (status)`,
  `CREATE INDEX IF NOT EXISTS idx_approval_regdate ON approval (regdate DESC)`,

  // ── ROUTE : 결재선 (다중 회차 가능) ─────────────────────────────
  `CREATE TABLE IF NOT EXISTS route (
     objid             BIGINT PRIMARY KEY,
     target_objid      BIGINT,
     approval_objid    BIGINT,
     route_seq         BIGINT,
     approval_title    VARCHAR(500),
     approval_desc     TEXT,
     system_type       VARCHAR(50),
     writer            VARCHAR(80),
     regdate           TIMESTAMP DEFAULT NOW(),
     status            VARCHAR(20) DEFAULT 'inProcess'
   )`,
  `CREATE INDEX IF NOT EXISTS idx_route_target   ON route (target_objid)`,
  `CREATE INDEX IF NOT EXISTS idx_route_approval ON route (approval_objid)`,
  `CREATE INDEX IF NOT EXISTS idx_route_status   ON route (status)`,

  // ── APPROVAL_TARGET : (결재대상 ↔ approval) N:N 매핑 ───────────
  `CREATE TABLE IF NOT EXISTS approval_target (
     objid                BIGINT PRIMARY KEY,
     master_target_objid  BIGINT,
     target_objid         BIGINT,
     approval_objid       BIGINT,
     writer               VARCHAR(80),
     regdate              TIMESTAMP DEFAULT NOW()
   )`,
  `CREATE INDEX IF NOT EXISTS idx_appr_tgt_target   ON approval_target (target_objid)`,
  `CREATE INDEX IF NOT EXISTS idx_appr_tgt_approval ON approval_target (approval_objid)`,

  // ── INBOXTASK : 결재함 (각 결재자 task) ────────────────────────
  `CREATE TABLE IF NOT EXISTS inboxtask (
     objid           BIGINT PRIMARY KEY,
     seq             BIGINT,
     approval_type   VARCHAR(20),      -- 결재(approval), 합의(agree), 참조(refer), 통보(notice) 등
     target_objid    BIGINT,
     approval_objid  BIGINT,
     route_objid     BIGINT,
     target_user_id  VARCHAR(80),
     comment         TEXT,
     status          VARCHAR(20),      -- ready / approve / reject / pending / hold / complete
     regdate         TIMESTAMP DEFAULT NOW(),
     editdate        TIMESTAMP
   )`,
  `CREATE INDEX IF NOT EXISTS idx_inbox_user     ON inboxtask (target_user_id)`,
  `CREATE INDEX IF NOT EXISTS idx_inbox_approval ON inboxtask (approval_objid)`,
  `CREATE INDEX IF NOT EXISTS idx_inbox_route    ON inboxtask (route_objid)`,
  `CREATE INDEX IF NOT EXISTS idx_inbox_status   ON inboxtask (status)`,

  // ── APPROVAL_KIND : 결재 종류 마스터 (target_type → 한글 라벨) ──
  `CREATE TABLE IF NOT EXISTS approval_kind (
     target_type     VARCHAR(50) PRIMARY KEY,
     target_name     VARCHAR(120),
     description     VARCHAR(500),
     status          VARCHAR(20) DEFAULT 'active'
   )`,
  `INSERT INTO approval_kind (target_type, target_name, description) VALUES
     ('ECR_MNG',      'ECR 결재',      'Engineering Change Request'),
     ('CUSTOMER_MNG', '고객 CS 결재',  'Customer Service Management'),
     ('EO_MNG',       'EO 결재',       'Engineering Order'),
     ('CSM',          'CSM 결재',      'CS Master'),
     ('ASMNG',        'AS 결재',       'AS Management'),
     ('SALES_REQUEST','영업요청 결재', 'Sales Request'),
     ('PURCHASE_ORDER','구매발주 결재','Purchase Order')
   ON CONFLICT (target_type) DO NOTHING`,

  // ── AMARANTH_APPROVAL : Wehago/Amaranth SSO 매핑 ────────────────
  //   우리 시스템 결재(approval.objid) ↔ 아마란스 docId / approKey 연결
  // target_objid: wace 운영은 VARCHAR — `T.OBJID::VARCHAR = AMR_ORDER.TARGET_OBJID` (contractMgmt.xml:662)
  //                vexplor_rps contract_mgmt.objid가 varchar(`CM-...`) 형식이라 cast 불가 → wace와 동일하게 VARCHAR로 유지
  `CREATE TABLE IF NOT EXISTS amaranth_approval (
     objid             BIGINT PRIMARY KEY,
     approval_objid    BIGINT,
     target_objid      VARCHAR(80),
     target_type       VARCHAR(50),
     appro_key         VARCHAR(120),   -- 외부시스템 연동키 ('UB_' + UUID)
     out_process_code  VARCHAR(80),    -- 아마란스 결재연동코드
     form_id           VARCHAR(80),    -- 아마란스 양식코드
     amaranth_doc_id   VARCHAR(120),   -- 상신 후 받은 docId
     status            VARCHAR(20) DEFAULT 'pending',
     emp_seq           VARCHAR(40),
     comp_seq          VARCHAR(40),
     dept_seq          VARCHAR(40),
     writer            VARCHAR(80),
     sso_url           TEXT,
     regdate           TIMESTAMP DEFAULT NOW(),
     editdate          TIMESTAMP
   )`,
  `CREATE INDEX IF NOT EXISTS idx_ama_appr_approval ON amaranth_approval (approval_objid)`,
  `CREATE INDEX IF NOT EXISTS idx_ama_appr_target   ON amaranth_approval (target_objid)`,
  `CREATE INDEX IF NOT EXISTS idx_ama_appr_doc      ON amaranth_approval (amaranth_doc_id)`,
];

export async function ensureApprovalTables(): Promise<void> {
  const pool = getPool();
  let success = 0;
  let failed = 0;

  for (const stmt of STATEMENTS) {
    try {
      await pool.query(stmt);
      success++;
    } catch (e: any) {
      failed++;
      logger.warn(`[approvalMigration] 실패 (계속 진행): ${e?.message?.slice(0, 200)}`);
    }
  }

  logger.info(`🌱 결재 시스템 마이그레이션 완료: 성공 ${success}건 / 실패 ${failed}건`);
}
