-- Migration 047: Update Ausrüstungsanfrage (Internal Orders) system
-- - Add bezeichnung column to ausruestung_anfragen
-- - Rename permissions: approve_requests → approve, view_overview → view_all
-- - Add new permission: ausruestungsanfrage:edit

-- 1. Add bezeichnung column to anfragen table
ALTER TABLE ausruestung_anfragen ADD COLUMN IF NOT EXISTS bezeichnung TEXT;

-- 2. Rename permissions
UPDATE permissions SET id = 'ausruestungsanfrage:approve'
  WHERE id = 'ausruestungsanfrage:approve_requests';

UPDATE permissions SET id = 'ausruestungsanfrage:view_all'
  WHERE id = 'ausruestungsanfrage:view_overview';

-- 3. Add new edit permission
INSERT INTO permissions (id, feature_group_id, label, description, sort_order)
VALUES ('ausruestungsanfrage:edit', 'ausruestungsanfrage', 'Alle Anfragen bearbeiten', 'Alle Anfragen bearbeiten (unabhängig von Status/Besitzer)', 10)
ON CONFLICT (id) DO NOTHING;

-- 4. Grant new edit permission to groups that had approve_requests (now approve)
INSERT INTO group_permissions (authentik_group, permission_id)
SELECT gp.authentik_group, 'ausruestungsanfrage:edit'
FROM group_permissions gp
WHERE gp.permission_id = 'ausruestungsanfrage:approve'
ON CONFLICT DO NOTHING;
