<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureHasPermission
{
    public function handle(Request $request, Closure $next, string $permissionKeys): Response
    {
        $user = $request->user();

        if (! $user) {
            abort(403);
        }

        $keys = array_values(array_filter(explode('|', $permissionKeys)));

        if (empty($keys)) {
            abort(403);
        }

        $expandedKeys = [];
        foreach ($keys as $key) {
            $key = (string) $key;
            $expandedKeys[] = $key;

            if (str_ends_with($key, '.view')) {
                $resourceKey = substr($key, 0, -strlen('.view'));
                $expandedKeys[] = $resourceKey.'.create';
                $expandedKeys[] = $resourceKey.'.update';
                $expandedKeys[] = $resourceKey.'.delete';
            }
        }

        $expandedKeys = array_values(array_unique($expandedKeys));

        if (! $user->hasAnyPermission($expandedKeys)) {
            abort(403);
        }

        return $next($request);
    }
}
