<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Permission;

/**
 * Registers the medward.* Spatie permissions (surfaced in the role editor via
 * DataController::user_permissions(), mirroring MedBilling). Admins bypass them
 * through the core Gate::before for Admin#<business_id>.
 *
 * firstOrCreate keeps the migration idempotent across repair / re-runs.
 */
return new class extends Migration {
    /** @var string[] */
    private $permissions = [
        'medward.wards.manage',
        'medward.admission.create',
        'medward.admission.discharge',
        'medward.mar.administer',
        'medward.icu.chart',
        'medward.board.view',
    ];

    public function up(): void
    {
        if (! Schema::hasTable('permissions')) {
            return; // Spatie tables not migrated yet — permissions land via module repair/seed later.
        }

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

    public function down(): void
    {
        if (! Schema::hasTable('permissions')) {
            return;
        }

        Permission::whereIn('name', $this->permissions)
            ->where('guard_name', 'web')
            ->delete();
    }
};
