<?php

namespace App\Http\Controllers\Api\Concerns;

use App\Models\Member;
use App\Models\Organization;
use App\Services\Care\CarePermissions;
use App\Services\Care\OrganizationResolver;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

trait ScopesApiToAccount
{
    /**
     * Tenant data owner — always the organization owner_ref.
     * Staff API tokens must scope to the employer tenant, not the staff public_id.
     */
    protected function ownerRef(Request $request): string
    {
        return (string) $this->organization($request)->owner_ref;
    }

    protected function actorRef(Request $request): string
    {
        return (string) $request->user()->public_id;
    }

    protected function organization(Request $request): Organization
    {
        $organization = app(OrganizationResolver::class)->resolveForUser($request->user());
        abort_unless($organization, 404);

        return $organization;
    }

    protected function member(Request $request): ?Member
    {
        return app(OrganizationResolver::class)->memberFor($request->user(), $this->organization($request));
    }

    protected function authorizeAbility(Request $request, string $ability): void
    {
        abort_unless(
            app(CarePermissions::class)->can($this->member($request), $ability),
            403,
        );
    }

    protected function authorizeOwner(Request $request, Model $model): void
    {
        abort_unless($model->getAttribute('owner_ref') === $this->ownerRef($request), 404);
    }
}
