-- Migration 063: Split fahrzeugbuchungen into its own feature group
-- Moves kalender:view_bookings, kalender:manage_bookings, kalender:widget_bookings
-- into a new 'fahrzeugbuchungen' feature group with cleaner permission names.

-- 1. Add new feature group
INSERT INTO feature_groups (id, label, sort_order)
VALUES ('fahrzeugbuchungen', 'Fahrzeugbuchungen', 2)
ON CONFLICT (id) DO NOTHING;

-- Shift existing groups down to make room (kalender stays 1, fahrzeugbuchungen is 2)
UPDATE feature_groups SET sort_order = sort_order + 1
WHERE id NOT IN ('kalender', 'fahrzeugbuchungen') AND sort_order >= 2;

-- 2. Add new permissions
INSERT INTO permissions (id, feature_group_id, label, description, sort_order) VALUES
  ('fahrzeugbuchungen:view',   'fahrzeugbuchungen', 'Ansehen',        'Buchungsliste anzeigen',                  1),
  ('fahrzeugbuchungen:create', 'fahrzeugbuchungen', 'Erstellen',      'Neue Fahrzeugbuchungen anlegen',           2),
  ('fahrzeugbuchungen:manage', 'fahrzeugbuchungen', 'Verwalten',      'Buchungen bearbeiten, stornieren, löschen; Kategorien verwalten', 3),
  ('fahrzeugbuchungen:widget', 'fahrzeugbuchungen', 'Widget',         'Dashboard-Widget für Fahrzeugbuchungen',   4)
ON CONFLICT (id) DO NOTHING;

-- 3. Migrate existing group_permissions
--    kalender:view_bookings  → fahrzeugbuchungen:view
--    kalender:manage_bookings → fahrzeugbuchungen:manage + fahrzeugbuchungen:create + fahrzeugbuchungen:view
--    kalender:widget_bookings → fahrzeugbuchungen:widget

INSERT INTO group_permissions (authentik_group, permission_id)
SELECT authentik_group, 'fahrzeugbuchungen:view'
FROM group_permissions
WHERE permission_id = 'kalender:view_bookings'
ON CONFLICT DO NOTHING;

INSERT INTO group_permissions (authentik_group, permission_id)
SELECT authentik_group, 'fahrzeugbuchungen:create'
FROM group_permissions
WHERE permission_id = 'kalender:manage_bookings'
ON CONFLICT DO NOTHING;

INSERT INTO group_permissions (authentik_group, permission_id)
SELECT authentik_group, 'fahrzeugbuchungen:manage'
FROM group_permissions
WHERE permission_id = 'kalender:manage_bookings'
ON CONFLICT DO NOTHING;

INSERT INTO group_permissions (authentik_group, permission_id)
SELECT authentik_group, 'fahrzeugbuchungen:view'
FROM group_permissions
WHERE permission_id = 'kalender:manage_bookings'
ON CONFLICT DO NOTHING;

INSERT INTO group_permissions (authentik_group, permission_id)
SELECT authentik_group, 'fahrzeugbuchungen:widget'
FROM group_permissions
WHERE permission_id = 'kalender:widget_bookings'
ON CONFLICT DO NOTHING;

-- 4. Remove old kalender booking permissions
DELETE FROM group_permissions WHERE permission_id IN (
  'kalender:view_bookings', 'kalender:manage_bookings', 'kalender:widget_bookings'
);
DELETE FROM permissions WHERE id IN (
  'kalender:view_bookings', 'kalender:manage_bookings', 'kalender:widget_bookings'
);
