-- 012_einvoices.sql
-- v0.6 (2026-05-07)
-- 전자세금계산서 발행 이력 테이블 — 국세청 e-세로 직접 연동 + 향후 다른 어댑터 호환

BEGIN;

CREATE TABLE IF NOT EXISTS momo_einvoices (
  objid              TEXT PRIMARY KEY,
  order_objid        TEXT,                          -- 연결된 발주(있으면)
  customer_objid     TEXT NOT NULL,                 -- user_info.user_id (공급받는자)
  invoice_kind       VARCHAR(20) NOT NULL DEFAULT 'TAX',     -- TAX(세금계산서) / TAXFREE(계산서) / RECEIPT(영수)
  invoice_type       VARCHAR(20) NOT NULL DEFAULT 'NORMAL',  -- NORMAL / MODIFIED(수정) / CANCELED(취소)
  issue_method       VARCHAR(20) NOT NULL DEFAULT 'NTS',     -- NTS(국세청 직접) / POPBILL / MANUAL
  -- 공급자
  supplier_biz_no    VARCHAR(20),
  supplier_name      VARCHAR(200),
  supplier_ceo       VARCHAR(100),
  supplier_address   TEXT,
  supplier_business  VARCHAR(100),                  -- 업태
  supplier_item      VARCHAR(100),                  -- 종목
  -- 공급받는자
  buyer_biz_no       VARCHAR(20),
  buyer_name         VARCHAR(200),
  buyer_ceo          VARCHAR(100),
  buyer_address      TEXT,
  buyer_email        VARCHAR(200),
  buyer_phone        VARCHAR(50),
  -- 금액
  total_supply       NUMERIC(15,2) NOT NULL DEFAULT 0,
  total_vat          NUMERIC(15,2) NOT NULL DEFAULT 0,
  total_amount       NUMERIC(15,2) NOT NULL DEFAULT 0,
  -- 국세청 식별자
  nts_invoice_no     VARCHAR(40),                   -- 국세청 승인번호 (24자리)
  nts_response_code  VARCHAR(10),                   -- 응답코드
  nts_response_msg   TEXT,
  nts_sent_at        TIMESTAMP,                     -- 국세청 전송 시각
  nts_acknowledged   CHAR(1) DEFAULT 'N',           -- 승인 여부
  -- 상태
  status             VARCHAR(20) NOT NULL DEFAULT 'DRAFT',
    -- DRAFT(작성중) / QUEUED(전송대기) / SENT(전송완료) / ACK(승인완료) / FAIL(실패) / CANCELED(취소)
  issue_date         DATE NOT NULL DEFAULT CURRENT_DATE,
  -- 원본 XML / 응답 (디버깅용)
  request_xml        TEXT,
  response_xml       TEXT,
  -- 메타
  memo               TEXT,
  is_del             CHAR(1) DEFAULT 'N',
  regdate            TIMESTAMP DEFAULT NOW(),
  regid              TEXT,
  update_date        TIMESTAMP,
  update_id          TEXT
);
CREATE INDEX IF NOT EXISTS idx_momo_einvoices_order   ON momo_einvoices(order_objid);
CREATE INDEX IF NOT EXISTS idx_momo_einvoices_buyer   ON momo_einvoices(customer_objid, issue_date);
CREATE INDEX IF NOT EXISTS idx_momo_einvoices_status  ON momo_einvoices(status, issue_date);
CREATE INDEX IF NOT EXISTS idx_momo_einvoices_nts     ON momo_einvoices(nts_invoice_no);

CREATE TABLE IF NOT EXISTS momo_einvoice_items (
  objid          TEXT PRIMARY KEY,
  einvoice_objid TEXT NOT NULL REFERENCES momo_einvoices(objid) ON DELETE CASCADE,
  seq            INT NOT NULL,
  item_date      DATE,
  item_name      VARCHAR(200) NOT NULL,
  spec           VARCHAR(100),
  qty            NUMERIC(15,2),
  unit_price     NUMERIC(15,2),
  supply_amount  NUMERIC(15,2) NOT NULL DEFAULT 0,
  vat_amount     NUMERIC(15,2) NOT NULL DEFAULT 0,
  remark         VARCHAR(200)
);
CREATE INDEX IF NOT EXISTS idx_momo_einvoice_items ON momo_einvoice_items(einvoice_objid, seq);

COMMIT;
