<?php

function selfserve_eligibility_route_source(): string
{
    $route = file_get_contents(app_path('routes/departmentSelfserveVehicleConditionsRoute.php'));
    if ($route === false) {
        throw new RuntimeException('departmentSelfserveVehicleConditionsRoute.php not found');
    }

    return $route;
}

function selfserve_eligibility_route_block(string $route, string $method, string $path): string
{
    $start = strpos($route, "\$this->{$method}('{$path}'");
    if ($start === false) {
        throw new RuntimeException("Route block not found: {$method} {$path}");
    }

    $nextComment = strpos($route, "\n        /**", $start + 1);
    if ($nextComment === false) {
        return substr($route, $start);
    }

    return substr($route, $start, $nextComment - $start);
}

function selfserve_eligibility_method_block(string $route, string $signature): string
{
    $start = strpos($route, $signature);
    if ($start === false) {
        throw new RuntimeException("Method not found: {$signature}");
    }

    $nextMethod = strpos($route, "\n    private function ", $start + strlen($signature));
    if ($nextMethod === false) {
        return substr($route, $start);
    }

    return substr($route, $start, $nextMethod - $start);
}

it('authorizes customer eligibility preview lanes before returning task attachments', function (): void {
    $route = selfserve_eligibility_route_source();
    $allowedBlock = selfserve_eligibility_route_block($route, 'get', '/department/selfserve/vehicle/allowed');
    $assertBlock = selfserve_eligibility_method_block($route, 'private function assertLaneAccess(');

    expect($allowedBlock)->toContain('$lane = $this->assertLaneAccess($user, $lane_id, $has_global, $has_own);')
        ->and($allowedBlock)->toContain('previewVehicleEligibility($lane_id, $reg, $customer_number, $vehicle_type_id, [')
        ->and($allowedBlock)->toContain("'subuser_id' => \$subuser_id")
        ->and(strpos($allowedBlock, '$lane = $this->assertLaneAccess($user, $lane_id, $has_global, $has_own);'))
        ->toBeLessThan(strpos($allowedBlock, 'previewVehicleEligibility($lane_id, $reg, $customer_number, $vehicle_type_id, ['));

    expect($assertBlock)->toContain('bool $hasGlobalPermission = true')
        ->and($assertBlock)->toContain('bool $hasOwnPermission = false')
        ->and($assertBlock)->toContain('if ($hasGlobalPermission && $user !== null && $this->userHasLaneDepartmentAccess($user, $lane))')
        ->and($assertBlock)->toContain('if ($hasOwnPermission && $this->isCustomerSelfServeLaneEnabled($lane))')
        ->and($assertBlock)->toContain('$this->forbidDepartmentAccess($lane_department_id);')
        ->and($assertBlock)->toContain('$response->forbidden([$elevatedPermission]);');
});
