-- ============================================================================
-- 余额告警通知渠道（支持钉钉 / 飞书 / 企业微信 / Bark / 通用 Webhook）
-- ============================================================================

CREATE TABLE IF NOT EXISTS alert_notify_channels (
	id BIGSERIAL PRIMARY KEY,
	created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
	updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
	deleted_at TIMESTAMPTZ,
	merchant_id BIGINT NOT NULL,
	channel_type VARCHAR(32) NOT NULL,
	name VARCHAR(64) NOT NULL DEFAULT '',
	config TEXT NOT NULL DEFAULT '{}',
	enabled BOOLEAN NOT NULL DEFAULT true
);

CREATE INDEX IF NOT EXISTS idx_alert_notify_channels_merchant ON alert_notify_channels (merchant_id);

-- 历史 merchant_alert_configs.webhook_url 迁移为通用 webhook 渠道
INSERT INTO alert_notify_channels (merchant_id, channel_type, name, config, enabled)
SELECT merchant_id, 'webhook', '原 Webhook', json_build_object('webhook_url', webhook_url), true
FROM merchant_alert_configs
WHERE webhook_url <> ''
ON CONFLICT DO NOTHING;
