-- V115: 지급대상건 구성·수정 (P12 §2)
--       payment_batch / payment_batch_item 테이블
--       메뉴 PAYMENT_TARGET (GRP_SETTLE 하위, sort_order 120)
--       권한 READ/CREATE/UPDATE/EXECUTE + 역할부여 (V113 패턴 동일)
--       공통코드 PAYMENT_BATCH_STATUS (V96/V111 패턴, ON CONFLICT DO NOTHING 멱등)

-- ============================================================
-- 1. payment_batch (지급대상 배치)
-- ============================================================

CREATE TABLE payment_batch (
    batch_id       BIGSERIAL      PRIMARY KEY,
    settle_month   CHAR(6)        NOT NULL,
    batch_name     VARCHAR(100)   NOT NULL,
    status         VARCHAR(20)    NOT NULL  DEFAULT 'DRAFT',
    total_count    INT            NOT NULL  DEFAULT 0,
    total_payable  NUMERIC(15,2)  NOT NULL  DEFAULT 0,
    created_at     TIMESTAMP      NOT NULL  DEFAULT now(),
    created_by     BIGINT,
    finalized_at   TIMESTAMP,
    finalized_by   BIGINT,
    updated_at     TIMESTAMP,
    CONSTRAINT chk_payment_batch_status CHECK (status IN ('DRAFT', 'FINALIZED', 'CANCELLED'))
);

CREATE INDEX idx_payment_batch_month_status ON payment_batch (settle_month, status);

-- ============================================================
-- 2. payment_batch_item (지급대상건)
-- ============================================================

CREATE TABLE payment_batch_item (
    item_id         BIGSERIAL      PRIMARY KEY,
    batch_id        BIGINT         NOT NULL  REFERENCES payment_batch(batch_id),
    settle_id       BIGINT         NOT NULL  REFERENCES settle_master(settle_id),
    agent_id        BIGINT         NOT NULL  REFERENCES agent(agent_id),
    payable_amount  NUMERIC(15,2)  NOT NULL,
    included        BOOLEAN        NOT NULL  DEFAULT true,
    exclude_reason  VARCHAR(300),
    created_at      TIMESTAMP      NOT NULL  DEFAULT now(),
    CONSTRAINT uq_payment_batch_item UNIQUE (batch_id, settle_id)
);

CREATE INDEX idx_payment_batch_item_batch ON payment_batch_item (batch_id);

-- ============================================================
-- 3. 메뉴 INSERT: PAYMENT_TARGET (GRP_SETTLE 하위 PAGE)
-- ============================================================

INSERT INTO menu (parent_menu_id, menu_code, menu_name, menu_type, menu_path, component_path, menu_level, sort_order)
SELECT p.menu_id, x.code, x.name, 'PAGE', x.path, x.cmpt, 2, x.sort
FROM menu p
JOIN (VALUES
    ('PAYMENT_TARGET', '지급대상관리', '/settle/payment-target', 'settle/PaymentTarget', 120)
) AS x(code, name, path, cmpt, sort)
ON p.menu_code = 'GRP_SETTLE'
WHERE NOT EXISTS (SELECT 1 FROM menu WHERE menu_code = x.code);

-- ============================================================
-- 4. 메뉴 권한 항목 등록 (READ / CREATE / UPDATE / EXECUTE)
-- ============================================================

INSERT INTO menu_permission (menu_id, perm_code, perm_name, sort_order)
SELECT m.menu_id, p.code, p.name, p.sort
FROM menu m
CROSS JOIN (VALUES
    ('READ',    '조회', 10),
    ('CREATE',  '등록', 20),
    ('UPDATE',  '수정', 30),
    ('EXECUTE', '확정', 40)
) AS p(code, name, sort)
WHERE m.menu_code = 'PAYMENT_TARGET'
ON CONFLICT (menu_id, perm_code) DO NOTHING;

-- ============================================================
-- 5. 역할별 권한 부여
-- ============================================================

-- SUPER_ADMIN / ADMIN — 전체 권한 (READ / CREATE / UPDATE / EXECUTE)
INSERT INTO role_menu_permission (role_id, menu_id, perm_code, is_granted)
SELECT r.role_id, mp.menu_id, mp.perm_code, 'Y'
FROM role r
CROSS JOIN menu_permission mp
JOIN menu m ON m.menu_id = mp.menu_id
WHERE r.role_code IN ('SUPER_ADMIN', 'ADMIN')
  AND m.menu_code = 'PAYMENT_TARGET'
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;

-- MANAGER — READ 만
INSERT INTO role_menu_permission (role_id, menu_id, perm_code, is_granted)
SELECT r.role_id, mp.menu_id, mp.perm_code, 'Y'
FROM role r
CROSS JOIN menu_permission mp
JOIN menu m ON m.menu_id = mp.menu_id
WHERE r.role_code = 'MANAGER'
  AND mp.perm_code = 'READ'
  AND m.menu_code = 'PAYMENT_TARGET'
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;

-- ============================================================
-- 6. 공통코드: PAYMENT_BATCH_STATUS
-- ============================================================

INSERT INTO common_code_group (group_code, group_name, description, is_system, sort_order) VALUES
    ('PAYMENT_BATCH_STATUS', '지급배치상태', 'DRAFT=작성중/FINALIZED=확정/CANCELLED=취소', 'Y', 450)
ON CONFLICT (group_code) DO NOTHING;

INSERT INTO common_code (group_code, code, code_name, sort_order) VALUES
    ('PAYMENT_BATCH_STATUS', 'DRAFT',      '작성중', 10),
    ('PAYMENT_BATCH_STATUS', 'FINALIZED',  '확정',   20),
    ('PAYMENT_BATCH_STATUS', 'CANCELLED',  '취소',   30)
ON CONFLICT (group_code, code) DO NOTHING;
