<?php

use App\Models\Merchant;
use App\Models\WebhookDelivery;
use Illuminate\Contracts\Console\Kernel;

require __DIR__.'/../../vendor/autoload.php';

$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();

$email = $argv[1] ?? 'ahmadshahzaib2490+3@gmail.com';
$merchant = Merchant::where('email', $email)->firstOrFail();

$rows = WebhookDelivery::with('endpoint')
    ->whereHas('endpoint', fn ($query) => $query->where('merchant_id', $merchant->id))
    ->latest('id')
    ->limit(10)
    ->get()
    ->map(fn ($delivery) => [
        'id' => $delivery->id,
        'event_id' => $delivery->event_id,
        'event_type' => $delivery->payload['type'] ?? null,
        'status' => $delivery->status,
        'attempt_count' => $delivery->attempt_count,
        'last_response_code' => $delivery->last_response_code,
        'last_error' => $delivery->last_error,
        'endpoint_url' => $delivery->endpoint?->url,
        'created_at' => optional($delivery->created_at)->toIso8601String(),
    ]);

echo json_encode($rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL;
