-- Phase 6.2: per-route permission codes
-- Seeds the permission codes referenced by Phase 6 hardening middleware.
-- Safe to run multiple times (ON CONFLICT DO NOTHING).
--
-- Codes follow the plan's spec (CONSOLIDATION_PLAN.md §6.2):
--   product_import    — POST/PUT/DELETE on /api/import
--   data_management   — POST/PUT/DELETE on /api/csv (data-management.js)
--   ai_admin          — POST/PUT/DELETE on /api/ai-prompts, /api/ai-validation
--   templates_write   — POST/PUT/DELETE on /api/templates
--   image_admin       — POST/DELETE on /api/reusable-images
--   audit_read        — reserved for future read-gating on audit logs
--   acot_admin        — reserved for acot-server (Phase 5 scope)
--   klaviyo_* / meta_* / google_* / typeform_*  — reserved for dashboard-server (Phase 4 scope)
--
-- Admin users (is_admin = true) automatically pass any requirePermission() check,
-- so this migration does not auto-grant codes to admins. New non-admin users get
-- write access only when explicitly granted via the user-management UI.

INSERT INTO permissions (code, name, category, description) VALUES
  ('product_import', 'Product Import (write)', 'Imports',
   'Allows POST/PUT/DELETE on /api/import — uploads, deletes, generate-upc, etc.'),
  ('data_management', 'Data Management (write)', 'Data',
   'Allows POST/PUT/DELETE on /api/csv — CSV operations, full updates, full resets.'),
  ('ai_admin', 'AI Settings Admin', 'AI',
   'Allows write access to AI prompts and AI validation endpoints.'),
  ('templates_write', 'Template Editing', 'Templates',
   'Allows POST/PUT/DELETE on /api/templates.'),
  ('image_admin', 'Image Management', 'Images',
   'Allows uploads and deletions on /api/reusable-images.'),
  ('audit_read', 'Audit Log Access', 'Audit',
   'Reserved for future read-gating of import + product-editor audit logs.'),
  ('klaviyo_write', 'Klaviyo Write', 'Dashboard',
   'Reserved for dashboard-server: mutates Klaviyo lists/segments.'),
  ('klaviyo_admin', 'Klaviyo Admin', 'Dashboard',
   'Reserved for dashboard-server: triggers campaign syncs.'),
  ('meta_write', 'Meta Write', 'Dashboard',
   'Reserved for dashboard-server: Meta API write operations.'),
  ('google_write', 'Google Analytics Write', 'Dashboard',
   'Reserved for dashboard-server: GA write operations.'),
  ('typeform_write', 'Typeform Write', 'Dashboard',
   'Reserved for dashboard-server: Typeform write operations.'),
  ('acot_admin', 'ACOT Server Admin', 'ACOT',
   'Reserved for acot-server admin endpoints.')
ON CONFLICT (code) DO NOTHING;

-- Phase 2 deviation #6 cleanup: drop defunct frontend permissions if present.
-- These corresponded to the removed Aircall/Gorgias dashboards.
DELETE FROM user_permissions
 WHERE permission_id IN (
   SELECT id FROM permissions WHERE code IN ('dashboard:gorgias', 'dashboard:calls')
 );
DELETE FROM permissions WHERE code IN ('dashboard:gorgias', 'dashboard:calls');
