<?php

use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\Models\Permission;

/**
 * Register every meddoc.* permission into the ERP RBAC (spatie permissions),
 * idempotently. The role editor surfaces these via
 * DataController::user_permissions(); this migration (and MeddocPermissionSeeder)
 * guarantee the underlying rows exist so they can be assigned to roles.
 *
 * Admins bypass these checks via the core Gate::before for Admin#<business_id>.
 */
return new class extends Migration {
    public function up(): void
    {
        $permissions = [
            'meddoc.view',
            'meddoc.upload',
            'meddoc.manage_types',
            'meddoc.share',
            'meddoc.download_original',
            'meddoc.audit.view',
        ];

        foreach ($permissions as $name) {
            Permission::firstOrCreate([
                'name'       => $name,
                'guard_name' => 'web',
            ]);
        }
    }

    public function down(): void
    {
        Permission::whereIn('name', [
            'meddoc.view',
            'meddoc.upload',
            'meddoc.manage_types',
            'meddoc.share',
            'meddoc.download_original',
            'meddoc.audit.view',
        ])->delete();
    }
};
