<?php

declare(strict_types=1);

namespace App\Jobs\Paynl;

use App\Models\Merchant;
use App\Services\PaynlService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Paynl\Error\Error;

final class FetchStatistics implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public function handle(PaynlService $paynlService): void
    {
        try {
            $statistics = $paynlService->statistics();

            foreach ($statistics as $statistic) {
                $merchant = Merchant::query()
                    ->where('pay_id', '=', $statistic['id'])
                    ->first();

                if ($merchant === null) {
                    continue;
                }

                StoreTransactionsAndAttachToMerchant::dispatch($statistic['paymentMethods'], $merchant);
            }
        } catch (Error $exception) {
            $this->fail($exception);
        }
    }
}
