

-- Roles
INSERT INTO auth.role (name)
VALUES
  ('Admin'),
  ('User'),
  ('Editor'),
  ('Viewer')
ON CONFLICT (name) DO NOTHING;

-- Permissions
INSERT INTO auth.permission (name)
VALUES
  ('read'),
  ('write'),
  ('update'),
  ('delete'),
  ('share')
ON CONFLICT (name) DO NOTHING;

-- Service roles
WITH service_role_pairs (service_name, role_name) AS (
  VALUES
    ('Service A', 'Admin'),
    ('Service A', 'User'),
    ('Service B', 'User'),
    ('Service C', 'Editor'),
    ('UI Store', 'Viewer'),
    ('UI Store', 'Admin'),
    ('UI Store', 'User'),
    ('UI Store', 'Editor'),
    ('ui-store', 'Viewer')
)
INSERT INTO auth.service_roles (service_id, role_id)
SELECT s.id, r.id
FROM service_role_pairs sr
JOIN auth.services s ON s.name = sr.service_name
JOIN auth.role r ON r.name = sr.role_name
ON CONFLICT (service_id, role_id) DO NOTHING;

-- Role permissions
WITH role_permission_pairs (role_name, permission_name) AS (
  VALUES
    ('Admin', 'read'),
    ('Admin', 'write'),
    ('Admin', 'update'),
    ('Admin', 'delete'),
    ('User', 'read'),
    ('User', 'write'),
    ('User', 'update'),
    ('User', 'delete'),
    ('Editor', 'update'),
    ('Editor', 'read'),
    ('Viewer', 'read')
)
INSERT INTO auth.role_permission (role_id, permission_id)
SELECT r.id, p.id
FROM role_permission_pairs rpp
JOIN auth.role r ON r.name = rpp.role_name
JOIN auth.permission p ON p.name = rpp.permission_name
ON CONFLICT (role_id, permission_id) DO NOTHING;
