-- V35: 세금계산서 발행 이력 (tax_invoice)

-- ============================================================
-- 1. tax_invoice — 세금계산서 발행 이력
-- ============================================================

CREATE TABLE tax_invoice (
    invoice_id          BIGSERIAL       PRIMARY KEY,
    invoice_no          VARCHAR(50)     NOT NULL UNIQUE,            -- 발행 번호 (국세청 승인번호 등)
    invoice_type        VARCHAR(20)     NOT NULL,                   -- SUPPLY (매출) / PURCHASE (매입)
    issue_date          DATE            NOT NULL,                   -- 발행일
    supply_amount       NUMERIC(15,2)   NOT NULL,                   -- 공급가액
    tax_amount          NUMERIC(15,2)   NOT NULL,                   -- 세액 (공급가 × 10%)
    total_amount        NUMERIC(15,2)   NOT NULL,                   -- 합계액 (공급가 + 세액)

    -- 거래 상대방
    counterpart_name    VARCHAR(200)    NOT NULL,                   -- 거래 상대방 상호
    counterpart_biz_no  VARCHAR(20)     NOT NULL,                   -- 거래 상대방 사업자번호
    counterpart_rep     VARCHAR(100),                               -- 대표자명
    counterpart_addr    VARCHAR(500),                               -- 주소

    -- 내부 참조
    agent_id            BIGINT          REFERENCES agent(agent_id), -- 관련 설계사 (해당 시)
    settle_month        CHAR(6),                                    -- 관련 정산월 (YYYYMM, 해당 시)
    settle_id           BIGINT          REFERENCES settle_master(settle_id),

    -- 발행 메타
    description         VARCHAR(500),                               -- 품목/비고
    cancel_date         DATE,                                       -- 취소일 (NULL=유효)
    cancel_reason       VARCHAR(500),
    issued_by           BIGINT          NOT NULL,                   -- 발행 처리자
    created_at          TIMESTAMP       NOT NULL DEFAULT NOW(),
    updated_at          TIMESTAMP,

    CHECK (invoice_type IN ('SUPPLY', 'PURCHASE')),
    CHECK (total_amount = supply_amount + tax_amount)
);

COMMENT ON TABLE  tax_invoice                     IS '세금계산서 발행 이력 (매출/매입)';
COMMENT ON COLUMN tax_invoice.invoice_no          IS '세금계산서 발행번호 (국세청 승인번호)';
COMMENT ON COLUMN tax_invoice.invoice_type        IS 'SUPPLY=매출계산서 / PURCHASE=매입계산서';
COMMENT ON COLUMN tax_invoice.supply_amount       IS '공급가액';
COMMENT ON COLUMN tax_invoice.tax_amount          IS '부가세액 (공급가 × 10%)';
COMMENT ON COLUMN tax_invoice.total_amount        IS '합계 금액 = 공급가 + 부가세';
COMMENT ON COLUMN tax_invoice.counterpart_biz_no  IS '거래 상대방 사업자등록번호';
COMMENT ON COLUMN tax_invoice.cancel_date         IS '세금계산서 취소일 (NULL이면 유효 상태)';
COMMENT ON COLUMN tax_invoice.settle_month        IS '연관 정산월 (YYYYMM)';

CREATE INDEX idx_ti_issue_date  ON tax_invoice(issue_date DESC);
CREATE INDEX idx_ti_type_month  ON tax_invoice(invoice_type, settle_month);
CREATE INDEX idx_ti_agent       ON tax_invoice(agent_id, issue_date DESC);
CREATE INDEX idx_ti_biz_no      ON tax_invoice(counterpart_biz_no);

-- ============================================================
-- 2. 공통코드 INVOICE_TYPE
-- ============================================================

INSERT INTO common_code_group (group_code, group_name, description, is_system, sort_order) VALUES
    ('INVOICE_TYPE', '세금계산서유형', 'SUPPLY/PURCHASE', 'Y', 370)
ON CONFLICT (group_code) DO NOTHING;

INSERT INTO common_code (group_code, code, code_name, code_desc, sort_order) VALUES
    ('INVOICE_TYPE', 'SUPPLY',   '매출', '매출(공급) 세금계산서 — GA가 발행',   10),
    ('INVOICE_TYPE', 'PURCHASE', '매입', '매입 세금계산서 — GA가 수취',         20)
ON CONFLICT (group_code, code) DO NOTHING;
