-- 66_add_audit_permissions.sql
--
-- Rewritten in Phase 5 (BUG-20). The original file had three defects:
--
--   1. It inserted only (code, description). `permissions` declares `name`
--      NOT NULL and `group_name` NOT NULL with no defaults, so under
--      STRICT_TRANS_TABLES this fails with "Field 'name' doesn't have a
--      default value". Production runs MariaDB 10.4.32 with sql_mode
--      NO_ZERO_IN_DATE,NO_ZERO_DATE,NO_ENGINE_SUBSTITUTION (non-strict), so it
--      silently stored empty strings instead. The live `audit.view` row still
--      has name = '', group_name = '' and sort_order = 0. See blocker B8.
--   2. It was not idempotent: a second run raised a duplicate key error on
--      uk_code (1062).
--   3. Its second statement inserted into `role_permissions` selecting from
--      `roles`. Neither table exists in this schema and no migration creates
--      them. The real model is `admin_permissions(admin_id, permission_id)`;
--      there is no role-to-permission mapping table at all. That statement was
--      unreachable dead code and has been removed.
--
-- The ON DUPLICATE KEY UPDATE clause below also repairs the damaged production
-- row when this migration is next applied to `anode_battery`.
--
-- Granting `audit.view` to actual administrators must go through
-- `admin_permissions`. That is tracked as blocker B9 and is out of scope here.
--
-- sort_order 80 continues the observed grouping (products 1-4, orders 10-13,
-- payments 20-22, customers 30-32, inventory 40-41, reports 50-52,
-- settings 60-61, admins 70-73), placing the new `audit` group after `admins`.

INSERT INTO `permissions` (`code`, `name`, `group_name`, `description`, `sort_order`)
VALUES ('audit.view', 'مشاهده رویدادهای حسابرسی', 'audit', 'View audit events', 80)
ON DUPLICATE KEY UPDATE
    `name`        = VALUES(`name`),
    `group_name`  = VALUES(`group_name`),
    `description` = VALUES(`description`),
    `sort_order`  = VALUES(`sort_order`);
