-- kb-module: backfill kb:publish for existing tenants.
-- New tenants receive this via seedPermissions + seedSystemRoles (OWNER gets ALL;
-- ADMIN gets ALL except billing:manage and users:manage). MEMBER is not granted
-- kb:publish by default — publish is a distinct capability from kb:write.
-- Idempotent: ON CONFLICT DO NOTHING on permissions.key and role_permissions PK.

INSERT INTO permissions (key, description)
VALUES ('kb:publish', 'Publish and unpublish knowledge base articles')
ON CONFLICT (key) DO NOTHING;
--> statement-breakpoint

INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
CROSS JOIN permissions p
WHERE r.is_system_role = true
  AND r.name IN ('OWNER', 'ADMIN')
  AND p.key = 'kb:publish'
ON CONFLICT (role_id, permission_id) DO NOTHING;
