<?php

namespace App\Http\Controllers\Concerns;

use App\Models\Membership;
use App\Models\Organization;
use Illuminate\Http\Request;

trait ResolvesCurrentOrganization
{
    protected function currentOrganization(Request $request): ?Organization
    {
        return $request->user()
            ->memberships()
            ->with('organization')
            ->first()
            ?->organization;
    }

    protected function currentMembership(Request $request): ?Membership
    {
        return $request->user()
            ->memberships()
            ->with('organization')
            ->first();
    }

    protected function currentUserCan(Request $request, string $privilege): bool
    {
        $membership = $this->currentMembership($request);

        return $membership !== null
            && ($membership->role === 'owner' || $membership->hasPrivilege($privilege));
    }
}
