-- V53: 출금 신청 (withdraw_request)
--      정산 확정 후 설계사 수수료 출금 신청 → 결재 → 펌뱅킹 송신 → 결과 반영.
--      account_no는 AES 암호화 대상 (애플리케이션 EncryptTypeHandler 처리).

CREATE TABLE withdraw_request (
    request_id          BIGSERIAL    PRIMARY KEY,
    settle_master_id    BIGINT       NOT NULL REFERENCES settle_master(settle_id),
    agent_id            BIGINT       NOT NULL REFERENCES agent(agent_id),
    amount              NUMERIC(15,2) NOT NULL,
    requested_by        BIGINT       NOT NULL,
    -- 신청자 user_id (느슨한 참조)
    requested_at        TIMESTAMP    NOT NULL DEFAULT NOW(),
    approval_request_id BIGINT       REFERENCES approval_request(request_id),
    bank_code           VARCHAR(10)  NOT NULL,
    account_no          VARCHAR(200) NOT NULL,
    -- AES 암호화 대상 (EncryptTypeHandler)
    status              VARCHAR(20)  NOT NULL DEFAULT 'REQUESTED',
    sent_at             TIMESTAMP,
    -- 펌뱅킹 송신 시각
    completed_at        TIMESTAMP,
    -- 입금 완료 시각
    fail_reason         VARCHAR(500),
    created_at          TIMESTAMP    NOT NULL DEFAULT NOW(),
    updated_at          TIMESTAMP,
    CHECK (amount > 0),
    CHECK (status IN ('REQUESTED','APPROVED','SENT','COMPLETED','FAILED','CANCELLED'))
);

COMMENT ON TABLE  withdraw_request                   IS '출금 신청 — 정산 확정 후 수수료 출금 결재→펌뱅킹→완료 워크플로우';
COMMENT ON COLUMN withdraw_request.settle_master_id  IS '출금 기준 정산 FK (settle_master)';
COMMENT ON COLUMN withdraw_request.agent_id          IS '출금 대상 설계사 FK';
COMMENT ON COLUMN withdraw_request.amount            IS '출금 신청 금액';
COMMENT ON COLUMN withdraw_request.requested_by      IS '신청자 user_id';
COMMENT ON COLUMN withdraw_request.approval_request_id IS '결재 요청 FK (approval_request)';
COMMENT ON COLUMN withdraw_request.bank_code         IS '출금 은행 코드';
COMMENT ON COLUMN withdraw_request.account_no        IS '출금 계좌번호 (AES 암호화, EncryptTypeHandler 처리)';
COMMENT ON COLUMN withdraw_request.status            IS 'REQUESTED=신청/APPROVED=결재완료/SENT=펌뱅킹송신/COMPLETED=입금완료/FAILED=실패/CANCELLED=취소';
COMMENT ON COLUMN withdraw_request.sent_at           IS '펌뱅킹 송신 시각';
COMMENT ON COLUMN withdraw_request.completed_at      IS '입금 완료 확인 시각';
COMMENT ON COLUMN withdraw_request.fail_reason       IS '실패 사유 (FAILED 상태 시)';

CREATE INDEX idx_wr_agent_status    ON withdraw_request(agent_id, status);
CREATE INDEX idx_wr_settle          ON withdraw_request(settle_master_id);
CREATE INDEX idx_wr_status_date     ON withdraw_request(status, requested_at);
CREATE INDEX idx_wr_approval        ON withdraw_request(approval_request_id);
