CREATE TABLE IF NOT EXISTS notification_policy (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tenant_id BIGINT UNSIGNED NOT NULL,
    policy_name VARCHAR(128) NOT NULL,
    event_code VARCHAR(64) NOT NULL,
    channel VARCHAR(32) NOT NULL,
    receiver_type VARCHAR(64) NOT NULL,
    template_id BIGINT UNSIGNED NOT NULL,
    variables_json TEXT DEFAULT NULL,
    status VARCHAR(32) NOT NULL DEFAULT 'ENABLED',
    is_deleted TINYINT(1) NOT NULL DEFAULT 0,
    created_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY idx_tenant_event_status (tenant_id, event_code, status),
    KEY idx_tenant_template (tenant_id, template_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS notification_policy_event (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tenant_id BIGINT UNSIGNED NOT NULL,
    policy_id BIGINT UNSIGNED NOT NULL,
    event_code VARCHAR(64) NOT NULL,
    status VARCHAR(32) NOT NULL DEFAULT 'ENABLED',
    created_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uk_tenant_policy (tenant_id, policy_id),
    KEY idx_tenant_event (tenant_id, event_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO permission (id, permission_code, permission_name, module)
VALUES
    (1057, 'notification.policy.read', '查看通知策略', 'notification'),
    (1058, 'notification.policy.manage', '管理通知策略', 'notification')
ON DUPLICATE KEY UPDATE permission_name = VALUES(permission_name), module = VALUES(module);

INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
VALUES
    (58, 1, 101, 1057),
    (59, 1, 101, 1058)
ON DUPLICATE KEY UPDATE permission_id = VALUES(permission_id);
