<?php
namespace App\Http\Controllers\Api\V1;
use App\Application\Services\Webhooks\WebhookDestinationValidator;
use App\Http\Controllers\Controller;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Throwable;
final class WebhookProbeController extends Controller {
 public function __invoke(Request $r,WebhookDestinationValidator $validator){$data=$r->validate(['url'=>['required','url','max:2048'],'environment'=>['nullable','in:sandbox,live']]);$url=$data['url'];$live=($data['environment']??config('gateway.environment'))==='live';$started=microtime(true);try{$ips=$validator->validate($url,$live);$payload=json_encode(['type'=>'webhook.probe','created_at'=>now()->utc()->toIso8601String()],JSON_UNESCAPED_SLASHES);$res=Http::connectTimeout(config('gateway.webhooks.connect_timeout_seconds',3))->timeout(config('gateway.webhooks.read_timeout_seconds',10))->withOptions(['allow_redirects'=>!$live])->withHeaders(['Content-Type'=>'application/json','X-Gateway-Probe'=>'true'])->withBody($payload,'application/json')->post($url);return ApiResponse::success(['reachable'=>$res->successful(),'url'=>$url,'resolved_ips'=>$ips,'status_code'=>$res->status(),'response_body'=>substr($res->body(),0,1000),'duration_ms'=>(int)round((microtime(true)-$started)*1000)]);}catch(Throwable $e){return ApiResponse::success(['reachable'=>false,'url'=>$url,'error'=>$e->getMessage(),'duration_ms'=>(int)round((microtime(true)-$started)*1000)],200);} }
}