<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;use App\Jobs\DeliverMerchantWebhookJob;use App\Models\{WebhookDelivery,WebhookEndpoint};use App\Support\ApiResponse;use Illuminate\Http\Request;use Illuminate\Support\Str;
final class WebhookTestController extends Controller {public function __invoke(Request $r){$m=$r->attributes->get('merchant');$env=$r->attributes->get('environment');$endpoint=WebhookEndpoint::where('merchant_id',$m->id)->where('environment',$env)->where('status','active')->first();if(!$endpoint)return ApiResponse::error('VALIDATION_ERROR','No active webhook endpoint is configured.',400);$id='evt_'.Str::ulid();$payload=['id'=>$id,'type'=>'payment.test','created_at'=>now()->utc()->toIso8601String(),'test_mode'=>true,'data'=>['message'=>'Synthetic webhook delivery test']];$raw=json_encode($payload,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR);$delivery=WebhookDelivery::create(['event_id'=>$id,'endpoint_id'=>$endpoint->id,'payload'=>$payload,'raw_payload'=>$raw,'attempt_count'=>0,'status'=>'queued','next_attempt_at'=>now()]);DeliverMerchantWebhookJob::dispatch($delivery->id)->onQueue('merchant-webhooks')->afterCommit();return ApiResponse::success(['event_id'=>$id,'status'=>'queued','test_mode'=>true],202);}}
