<?php

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

/**
 * Permission for the AI medical assistant + assign it to the seeded Admin role.
 */
class AddClinicAiPermission extends Migration
{
    public function up()
    {
        Permission::findOrCreate('clinic.use_ai_assist', 'web');

        try {
            $admin = Role::where('name', 'Admin#1')->first();
            if ($admin) {
                $perm = Permission::where('name', 'clinic.use_ai_assist')->first();
                if ($perm && !$admin->hasPermissionTo($perm)) {
                    $admin->givePermissionTo($perm);
                }
            }
        } catch (\Throwable $e) {
            // Never let permission assignment break the migration.
        }
    }

    public function down()
    {
        Permission::where('name', 'clinic.use_ai_assist')->delete();
    }
}
