INSERT INTO notification_text_template (
    tenant_id,
    template_name,
    subject_template,
    title_template,
    content_template,
    status,
    is_deleted,
    created_by,
    updated_by
)
SELECT
    1,
    '用户创建邮件通知',
    '用户账号开通通知',
    '用户账号开通通知',
    CONCAT(
        '您好，$', '{userName}：\n',
        '您的系统账号已由管理员开通。\n',
        '租户名称：$', '{tenantName}\n',
        '租户编码：$', '{tenantCode}\n',
        '登录地址：$', '{loginPath}\n',
        '登录账号：$', '{phone}\n',
        '通知邮箱：$', '{email}\n',
        '账号有效期：$', '{validFrom} ~ $', '{validTo}\n',
        '请首次登录后及时修改密码。'
    ),
    'ENABLED',
    0,
    0,
    0
WHERE NOT EXISTS (
    SELECT 1
    FROM notification_text_template
    WHERE tenant_id = 1
      AND template_name = '用户创建邮件通知'
      AND is_deleted = 0
);

INSERT INTO notification_policy (
    tenant_id,
    policy_name,
    event_code,
    channel,
    receiver_type,
    template_id,
    variables_json,
    status,
    is_deleted,
    created_by,
    updated_by
)
SELECT
    1,
    '用户创建邮件通知策略',
    'USER_CREATED',
    'EMAIL',
    'TARGET_USER',
    t.id,
    NULL,
    'ENABLED',
    0,
    0,
    0
FROM notification_text_template t
WHERE t.tenant_id = 1
  AND t.template_name = '用户创建邮件通知'
  AND t.is_deleted = 0
  AND NOT EXISTS (
    SELECT 1
    FROM notification_policy p
    WHERE p.tenant_id = 1
      AND p.policy_name = '用户创建邮件通知策略'
      AND p.is_deleted = 0
  );

INSERT INTO notification_policy_event (
    tenant_id,
    policy_id,
    event_code,
    status,
    created_by,
    updated_by
)
SELECT
    1,
    p.id,
    'USER_CREATED',
    p.status,
    0,
    0
FROM notification_policy p
WHERE p.tenant_id = 1
  AND p.policy_name = '用户创建邮件通知策略'
  AND p.is_deleted = 0
  AND NOT EXISTS (
    SELECT 1
    FROM notification_policy_event e
    WHERE e.tenant_id = 1
      AND e.policy_id = p.id
  );
