<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Role Management — real permissions data, honestly scoped. This table
 * controls per-role NAV VISIBILITY of each module/section (see
 * Config\Lookups::$permissionModules and RoleManagementController) — it
 * is NOT a replacement for the actual security boundary, which remains
 * the three `role:manager|front_desk|fnb` route-group filters hardcoded
 * in Routes.php (see e.g. the "front-of-house (manager + front_desk
 * only)" group). Those groups are what a role can reach at all; this
 * table only controls which of the modules within a role's already-
 * permitted set show up in their sidebar — real, editable, and verified
 * by whether the link actually (dis)appears, just not itself a second
 * access-control layer. Rewriting the route-level groups to be fully
 * dynamic per-module would be a much larger change and is out of scope
 * here.
 *
 * One row per (role, module_key) that's been explicitly toggled.
 * Absence of a row means "visible" (the default, matching the app's
 * behavior before this table existed) — RolePermissionModel::isAllowed()
 * falls back to true rather than requiring every combination to be
 * seeded, so nothing regresses until a manager actually changes something.
 */
class CreateRolePermissionsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'role' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
            ],
            'module_key' => [
                'type'       => 'VARCHAR',
                'constraint' => 50,
            ],
            'allowed' => [
                'type'       => 'TINYINT',
                'constraint' => 1,
                'default'    => 1,
            ],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
            'updated_at' => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey(['role', 'module_key']);
        $this->forge->createTable('role_permissions');
    }

    public function down()
    {
        $this->forge->dropTable('role_permissions', true);
    }
}
