<?php

namespace Modules\Core\Traits;

use Modules\Auth\Models\Permission;

trait HasModulePermissions
{
    protected function seedPermissions(
        string $module,
        array $permissions,
        string $guard = 'api'
    ): void {
        $sort = Permission::where('module', $module)->max('sorting_index') ?? 0;

        foreach ($permissions as $resource => $actions) {
            foreach ($actions as $action) {
                Permission::updateOrCreate(
                    [
                        'name' => "{$module}.{$resource}.{$action}",
                        'guard_name' => $guard,
                    ],
                    [
                        'module' => ucfirst($module),
                        'sorting_index' => ++$sort,
                    ]
                );
            }
        }
    }
}
