-- ===========================================================================
-- Migration: granular platform-admin roles + per-farm module access
-- Date: 2026-07-28
--
--  users.platform_perms  — JSON array of Platform sections an admin may use
--                          (farms, billing, support, system, migrate, admins).
--                          NULL = full access (the original/bootstrap super admins).
--  plans.modules         — JSON array of app modules a plan's farms get by default.
--                          NULL = all modules.
--  farms.modules         — JSON array overriding the plan default for one farm.
--                          NULL = inherit the plan (or all).
-- Effective farm modules = farms.modules ?? plan.modules ?? all. Enforced in
-- Auth::requirePermission for real farm users (platform operators are exempt).
-- schema.sql carries all three. Idempotent; safe to re-run.
-- ===========================================================================

SET @c = (SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'platform_perms');
SET @s = IF(@c = 0, 'ALTER TABLE users ADD COLUMN platform_perms JSON NULL AFTER is_platform_admin', 'DO 0');
PREPARE q FROM @s; EXECUTE q; DEALLOCATE PREPARE q;

SET @c = (SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'plans' AND COLUMN_NAME = 'modules');
SET @s = IF(@c = 0, 'ALTER TABLE plans ADD COLUMN modules JSON NULL AFTER sms_included', 'DO 0');
PREPARE q FROM @s; EXECUTE q; DEALLOCATE PREPARE q;

SET @c = (SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'farms' AND COLUMN_NAME = 'modules');
SET @s = IF(@c = 0, 'ALTER TABLE farms ADD COLUMN modules JSON NULL AFTER kind', 'DO 0');
PREPARE q FROM @s; EXECUTE q; DEALLOCATE PREPARE q;
