-- V77: 설계사 연말 지급명세서 (사업소득 지급명세서)
-- agent_annual_income(V63) 의 연 집계 데이터를 기반으로 설계사별 PDF/Excel 발급 마스터.

CREATE TABLE year_end_statement (
    statement_id     BIGSERIAL      PRIMARY KEY,
    agent_id         BIGINT         NOT NULL REFERENCES agent(agent_id),
    statement_year   INTEGER        NOT NULL,                       -- 신고 연도 (예: 2025)
    statement_type   VARCHAR(20)    NOT NULL DEFAULT 'INCOME_DEDUCTION',
                                                                    -- INCOME_DEDUCTION=사업소득 지급명세서
    total_income     NUMERIC(18,2)  NOT NULL DEFAULT 0,              -- agent_annual_income.total_income 캐시
    total_withheld   NUMERIC(18,2)  NOT NULL DEFAULT 0,              -- agent_annual_income.total_withheld 캐시
    total_local_tax  NUMERIC(18,2)  NOT NULL DEFAULT 0,
    file_path        VARCHAR(500),                                   -- 생성된 PDF/Excel 경로
    file_format      VARCHAR(10)    NOT NULL DEFAULT 'XLSX',         -- XLSX / PDF
    file_status      VARCHAR(15)    NOT NULL DEFAULT 'DRAFT',        -- DRAFT / GENERATED / SENT
    generated_at     TIMESTAMP,
    sent_at          TIMESTAMP,
    sent_to          VARCHAR(200),                                   -- 발송처(이메일/내부공유 등)
    created_at       TIMESTAMP      NOT NULL DEFAULT now(),
    created_by       BIGINT,
    updated_at       TIMESTAMP      NOT NULL DEFAULT now(),
    updated_by       BIGINT,
    UNIQUE (agent_id, statement_year, statement_type),
    CONSTRAINT chk_yes_format CHECK (file_format IN ('XLSX','PDF')),
    CONSTRAINT chk_yes_status CHECK (file_status IN ('DRAFT','GENERATED','SENT'))
);
COMMENT ON TABLE  year_end_statement                IS '설계사 연말 지급명세서 발급 마스터';
COMMENT ON COLUMN year_end_statement.statement_type IS 'INCOME_DEDUCTION=사업소득 지급명세서';
COMMENT ON COLUMN year_end_statement.file_status    IS 'DRAFT=대기, GENERATED=파일생성, SENT=발송완료';

CREATE INDEX idx_yes_year   ON year_end_statement(statement_year);
CREATE INDEX idx_yes_status ON year_end_statement(file_status);
CREATE INDEX idx_yes_agent  ON year_end_statement(agent_id, statement_year);
