<?php

namespace App\Http\Middleware;

use App\Services\Care\CarePermissions;
use App\Services\Care\OrganizationResolver;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureCareAbility
{
    public function __construct(
        protected OrganizationResolver $organizations,
        protected CarePermissions $permissions,
    ) {}

    public function handle(Request $request, Closure $next, string $ability): Response
    {
        $user = $request->user();
        abort_unless($user, 403);

        $organization = $this->organizations->resolveForUser($user);
        abort_unless($organization, 403);

        $member = $this->organizations->memberFor($user, $organization);
        abort_unless($this->permissions->can($member, $ability), 403);

        $request->attributes->set('care.organization', $organization);
        $request->attributes->set('care.member', $member);

        return $next($request);
    }
}
