<?php

namespace App\Concerns;

use App\Enums\WorkspaceUserRole;

trait AuthorizesPermissions
{
    /**
     * Authorize the current user has the given permission.
     *
     * Owner: always passes.
     * Worker: always fails (abort 404).
     * Manager: checks the permissions JSON column on workspace_user pivot.
     * Unknown permission keys default to false.
     */
    protected function authorizePermission(string $permission): void
    {
        $workspaceUser = auth()->user()->currentWorkspaceUser();

        if ($workspaceUser->role->is(WorkspaceUserRole::Owner)) {
            return;
        }

        if ($workspaceUser->role->is(WorkspaceUserRole::Worker)) {
            abort(404);
        }

        // Manager: check JSON permissions column
        if (! ($workspaceUser->permissions[$permission] ?? false)) {
            abort(404);
        }
    }
}
