-- V24: Create risk management tables
-- H2兼容版本
-- 风控规则表
CREATE TABLE IF NOT EXISTS risk_rules (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    risk_type VARCHAR(50) NOT NULL,
    condition_expr VARCHAR(1000) NOT NULL,
    action VARCHAR(50) NOT NULL,
    action_params VARCHAR(1000),
    status VARCHAR(20) NOT NULL DEFAULT 'ENABLED',
    priority INT NOT NULL DEFAULT 0,
    created_by BIGINT,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP DEFAULT NULL
);

CREATE INDEX IF NOT EXISTS idx_risk_type ON risk_rules(risk_type);
CREATE INDEX IF NOT EXISTS idx_status ON risk_rules(status);
CREATE INDEX IF NOT EXISTS idx_priority ON risk_rules(priority);

-- 风控告警表
CREATE TABLE IF NOT EXISTS risk_alerts (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    alert_type VARCHAR(50) NOT NULL,
    risk_level VARCHAR(20) NOT NULL,
    title VARCHAR(200) NOT NULL,
    description VARCHAR(1000),
    related_user_id BIGINT,
    related_activity_id BIGINT,
    related_rule_id BIGINT,
    related_data VARCHAR(1000),
    status VARCHAR(20) NOT NULL DEFAULT 'PENDING',
    handler_id BIGINT,
    handler_comment VARCHAR(1000),
    handled_at TIMESTAMP,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_alert_type ON risk_alerts(alert_type);
CREATE INDEX IF NOT EXISTS idx_risk_level ON risk_alerts(risk_level);
CREATE INDEX IF NOT EXISTS idx_alert_status ON risk_alerts(status);
CREATE INDEX IF NOT EXISTS idx_related_user ON risk_alerts(related_user_id);
CREATE INDEX IF NOT EXISTS idx_created_at ON risk_alerts(created_at);

-- 风控黑名单表
CREATE TABLE IF NOT EXISTS risk_blacklist (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    target_type VARCHAR(20) NOT NULL,
    target_value VARCHAR(255) NOT NULL,
    reason VARCHAR(500),
    expire_at TIMESTAMP,
    created_by BIGINT,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE (target_type, target_value)
);

CREATE INDEX IF NOT EXISTS idx_target_value ON risk_blacklist(target_value);
CREATE INDEX IF NOT EXISTS idx_expire_at ON risk_blacklist(expire_at);
