-- V23: 세무 처리 스키마 확장 + 세율 설정 + 공통코드

-- ============================================================
-- 1. agent 테이블 세무 컬럼 추가
-- ============================================================

ALTER TABLE agent
    ADD COLUMN tax_type     VARCHAR(20) NOT NULL DEFAULT 'BUSINESS_INCOME',
    ADD COLUMN business_no  VARCHAR(20),
    ADD COLUMN vat_type     VARCHAR(20) NOT NULL DEFAULT 'NONE';

ALTER TABLE agent
    ADD CONSTRAINT chk_agent_tax_type
        CHECK (tax_type IN ('BUSINESS_INCOME', 'OTHER_INCOME')),
    ADD CONSTRAINT chk_agent_vat_type
        CHECK (vat_type IN ('NONE', 'EXEMPT', 'TAXABLE'));

-- ============================================================
-- 2. payment 테이블 세무 컬럼 추가
-- ============================================================

ALTER TABLE payment
    ADD COLUMN income_tax_amount NUMERIC(15,2) NOT NULL DEFAULT 0,
    ADD COLUMN local_tax_amount  NUMERIC(15,2) NOT NULL DEFAULT 0,
    ADD COLUMN vat_amount        NUMERIC(15,2) NOT NULL DEFAULT 0,
    ADD COLUMN net_amount        NUMERIC(15,2);

-- ============================================================
-- 3. 표준 세율 system_config 추가
-- ============================================================

INSERT INTO system_config (config_key, config_value, config_group, value_type, description) VALUES
    ('TAX_RATE_BUSINESS_INCOME', '3.3',  'TAX', 'NUMBER', '사업소득 원천징수율(%) — 2024년 기준'),
    ('TAX_RATE_OTHER_INCOME',    '8.8',  'TAX', 'NUMBER', '기타소득 원천징수율(%) — 2024년 기준'),
    ('TAX_RATE_LOCAL_INCOME',    '10.0', 'TAX', 'NUMBER', '지방소득세율(%) — 원천세 기준'),
    ('TAX_RATE_VAT',             '10.0', 'TAX', 'NUMBER', '부가세율(%) — 일반과세자 적용')
ON CONFLICT (config_key) DO NOTHING;

-- ============================================================
-- 4. 공통코드 그룹 TAX_TYPE / VAT_TYPE 추가
-- ============================================================

INSERT INTO common_code_group (group_code, group_name, description, is_system, sort_order) VALUES
    ('TAX_TYPE', '소득세유형', 'BUSINESS_INCOME(사업소득) / OTHER_INCOME(기타소득)', 'Y', 190),
    ('VAT_TYPE',  '부가세유형', 'NONE / EXEMPT(면세) / TAXABLE(일반과세)',            'Y', 200)
ON CONFLICT (group_code) DO NOTHING;

INSERT INTO common_code (group_code, code, code_name, code_desc, sort_order) VALUES
    ('TAX_TYPE', 'BUSINESS_INCOME', '사업소득', '원천징수 3.3% 적용',         10),
    ('TAX_TYPE', 'OTHER_INCOME',    '기타소득', '원천징수 8.8% 적용',         20),
    ('VAT_TYPE',  'NONE',            '미지정',   '부가세 처리 없음',            10),
    ('VAT_TYPE',  'EXEMPT',          '면세사업자','부가세 면세 — 계산서 발행', 20),
    ('VAT_TYPE',  'TAXABLE',         '일반과세자','부가세 10% — 세금계산서',   30)
ON CONFLICT (group_code, code) DO NOTHING;
