CREATE TABLE IF NOT EXISTS in_app_notification (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tenant_id BIGINT UNSIGNED NOT NULL,
    receiver_ref VARCHAR(128) NOT NULL,
    receiver_user_id BIGINT UNSIGNED DEFAULT NULL,
    title VARCHAR(200) NOT NULL,
    content TEXT,
    payload_json TEXT,
    status VARCHAR(32) NOT NULL DEFAULT 'UNREAD',
    read_at DATETIME DEFAULT NULL,
    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_receiver_status_time (tenant_id, receiver_user_id, status, created_at),
    KEY idx_tenant_receiver_ref_time (tenant_id, receiver_ref, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO permission (id, permission_code, permission_name, module)
SELECT t.next_id, 'notification.inapp.read', '查看站内通知', 'notification'
FROM (SELECT IFNULL(MAX(id), 0) + 1 AS next_id FROM permission) t
WHERE NOT EXISTS (
    SELECT 1 FROM permission WHERE permission_code = 'notification.inapp.read'
);

INSERT INTO permission (id, permission_code, permission_name, module)
SELECT t.next_id, 'notification.inapp.mark-read', '标记站内通知已读', 'notification'
FROM (SELECT IFNULL(MAX(id), 0) + 1 AS next_id FROM permission) t
WHERE NOT EXISTS (
    SELECT 1 FROM permission WHERE permission_code = 'notification.inapp.mark-read'
);

UPDATE permission
SET permission_name = '查看站内通知', module = 'notification'
WHERE permission_code = 'notification.inapp.read';

UPDATE permission
SET permission_name = '标记站内通知已读', module = 'notification'
WHERE permission_code = 'notification.inapp.mark-read';

INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
SELECT t.next_id, 1, 101, p.id
FROM (SELECT IFNULL(MAX(id), 0) + 1 AS next_id FROM role_permission) t
JOIN permission p ON p.permission_code = 'notification.inapp.read'
WHERE NOT EXISTS (
    SELECT 1 FROM role_permission rp WHERE rp.tenant_id = 1 AND rp.role_id = 101 AND rp.permission_id = p.id
);

INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
SELECT t.next_id, 1, 101, p.id
FROM (SELECT IFNULL(MAX(id), 0) + 1 AS next_id FROM role_permission) t
JOIN permission p ON p.permission_code = 'notification.inapp.mark-read'
WHERE NOT EXISTS (
    SELECT 1 FROM role_permission rp WHERE rp.tenant_id = 1 AND rp.role_id = 101 AND rp.permission_id = p.id
);
